-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrintFromTopToBottom.java
45 lines (37 loc) · 1.05 KB
/
PrintFromTopToBottom.java
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
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;
import java.util.Queue;
import java.util.ArrayDeque;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
// Print a binary tree level by level, from left to right
public class Solution {
private ArrayList<Integer> res = new ArrayList<>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if (root == null) return res;
Queue<TreeNode> tq = new ArrayDeque<>();
TreeNode w = root;
tq.add(root);
while (!tq.isEmpty()) {
// while (!tq.isEmpty()) {
w = tq.poll();
if (w == null) break;
res.add(w.val);
// }
if (w.left != null) tq.add(w.left);
if (w.right != null) tq.add(w.right);
}
return res;
}
// private void PrintFromTopToBottom1(TreeNode root) {
// if (root == null) return null;
// res.add(root.val);
// }
}