问题描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
示例
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,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 int[] levelOrder(TreeNode root) {
if(root==null)
return new int[0];
Queue queue=new LinkedList ();
List list=new ArrayList ();
queue.add(root);
while(queue.size()>0) {
TreeNode node=queue.poll();
list.add(node.val);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
int[]a =new int[list.size()];
for(int i=0;i<a.length;i++) {
a[i]=list.get(i);
}
return a;}
}
![](https://img2020.cnblogs.com/blog/1740093/202103/1740093-20210302134529302-555413604.png)