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

题目:

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

 

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

    3
   / \
  9  20
    /  \
   15   7

返回:

[3,9,20,15,7]

 

提示:

  1. 节点总数 <= 1000

代码:

 

 

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public int[] levelOrder(TreeNode root) {
12         //空树
13         if(root==null){return new int[0]; }
14         //动态数组放入节点,模拟双端队列,同一层节点有序放入
15         List<TreeNode> list =new ArrayList<>();
16         list.add(root);
17         int i=0;
18         while(i<list.size()){
19             TreeNode temp=list.get(i);
20             if(temp.left!=null){list.add(temp.left);}
21             if(temp.right!=null){list.add(temp.right);}
22             i++;
23         }
24         //新建数组存放返回值
25         int len=list.size();
26         int[] res=new int[len];
27         int j=0;
28         for(TreeNode tn: list){
29             res[j++]=tn.val;
30         }
31         return res;
32     }
33 }

 

posted @ 2021-03-31 22:03  堤苏白  阅读(37)  评论(0)    收藏  举报