LeetCode-103. Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:c语言开根号的函数 编辑:程序博客网 时间:2024/06/13 22:54

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],
这里写图片描述
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

采用同LeetCode-102中方法一相似的思路,不同之处在于要判断当前的层数来决定最后是否将一层的所有数值反转。

class Solution {    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {        List<List<Integer>> res=new ArrayList<List<Integer>>();        if(root==null)            return res;        LinkedList<TreeNode> q=new LinkedList<TreeNode>();        q.add(root);        int level=1;        while(!q.isEmpty())        {            int levelNum=q.size();            List<Integer> tempList=new ArrayList<Integer>();            for(int i=0;i<levelNum;++i)            {                if(q.peek().left!=null)                    q.add(q.peek().left);                if(q.peek().right!=null)                    q.add(q.peek().right);                tempList.add(q.poll().val);            }            if(level%2==0)                Collections.reverse(tempList);            res.add(tempList);            level++;        }        return res;    }}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 永濑里美黑人在线播放 七濑麻衣 早川濑理奈图片 永濑唯作品 黄濑凉太 宫濑里子 加濑七穗 七濑恋 永濑唯所有作品 吉濑美智子 古濑领 永濑里美mifd107在线播放 濑亚 名濑美月 濑名爱理 濑名光莉日文 濑名步 濑名光莉在线 浅见濑名 水濑名雪 濑奈 高明濑粉 濑粉的做法 濑粉的做法及配方 广州手工濑粉的制作方法 濑粉图片 手工濑粉制作方法图解 永濑伊织 濒临 濒临的拼音 濒临灭绝 濒临拼音 濒临意思 濒临的意思 濒临读音 濒临怎么读 濒临灭绝动物 濒临灭绝的动物 泰禾集团濒临破产 濒临灭绝野生动物 邦泰集团濒临破产