博客园主题Bili2.0发布啦,快来看看(点击查看)

剑指 Offer 32 - III. 从上到下打印二叉树 III

剑指 Offer 32 - III. 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

复制代码
3

/
9 20
/
15 7
返回其层次遍历结果:

[
[3],
[20,9],
[15,7]
]

提示:

节点总数 <= 1000

复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
       
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root==null) return new  LinkedList<List<Integer>>();
            Queue<TreeNode> que = new LinkedList<>();
            List<List<Integer>> res = new ArrayList<>();
            que.add(root);
            int i = 0;
            while(!que.isEmpty())
            {
                int num =  que.size();
                List<Integer>  re = new ArrayList<>();
                while(num-->0)
                {
                    TreeNode node = que.poll();
                    System.out.println(node);
                    if(node.left!=null)
                    que.add(node.left);
                    if(node.right!=null)
                    que.add(node.right);
                    re.add(node.val);
                }
                if (i%2!=0) {
                    Collections.reverse(re);
                }
                i++;
                res.add(re);
            }
            return  res;




        }
}
posted @   小申同学  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2020-03-19 2019 12 02 section C one
点击右上角即可分享
微信分享提示