-
Notifications
You must be signed in to change notification settings - Fork 0
/
S22.java
46 lines (42 loc) · 1.26 KB
/
S22.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
46
package S21_30;
import PublicClass.TreeNode;
import PublicClass.Utils;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
/**
* 从上往下打印二叉树
* Created by Elvis on 2019/12/23.
*/
public class S22 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode n1 = new TreeNode(9);
TreeNode n2 = new TreeNode(7);
TreeNode n3 = new TreeNode(4);
TreeNode n4 = new TreeNode(2);
root.left = n1;
root.right = n2;
n2.left = n3;
// n2.right = n4;
Utils.printTree(root);
Utils.printArrayList(PrintFromTopToBottom(root));
}
public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if (root == null) return list;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while(!queue.isEmpty()) {
root = queue.poll();
list.add(root.val);
if (root.left != null) {
queue.add(root.left);
}
if (root.right != null) {
queue.add(root.right);
}
}
return list;
}
}