从上到下打印二叉树
题目:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 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 if(root == null){ 13 return new int[]{}; 14 } 15 Queue<TreeNode> queue = new LinkedList<>(); 16 queue.add(root); 17 List<Integer> list = new ArrayList(); 18 while(!queue.isEmpty()){ 19 TreeNode node = queue.poll(); 20 list.add(node.val); 21 if(node.left != null){ 22 queue.add(node.left); 23 } 24 if(node.right != null){ 25 queue.add(node.right); 26 } 27 } 28 int a [] = new int[list.size()]; 29 for(int i=0;i<list.size();i++){ 30 a[i] = list.get(i); 31 } 32 return a; 33 } 34 }