【剑指Offer】面试题32:从上到下打印二叉树

题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/

import java.util.*;

public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();

// 特殊输入的检查
if (root == null)
return res;

Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode n = q.remove();
res.add(n.val);
if (n.left != null)
q.add(n.left);
if (n.right != null)
q.add(n.right);
}

return res;
}
}