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

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

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

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

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

复制代码
3

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

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

复制代码
/**
 * 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);
            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);
                         
                }
                res.add(re);

            }
            return  res;




        }
}

提示:

节点总数 <= 1000

posted @   小申同学  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2020-03-19 2019 12 02 section C one
点击右上角即可分享
微信分享提示