剑指Offer_22

题目

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

解题思路

层序遍历二叉树

将ArrayList换成LinkedList效率会高一点……

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
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<>();
ArrayList<TreeNode> nodeList = new ArrayList<>();
if(root == null){
return ret;
}
nodeList.add(root);
while(!nodeList.isEmpty()){
TreeNode node = nodeList.get(0);
nodeList.remove(0);
ret.add(node.val);
if(node.left != null){
nodeList.add(node.left);
}
if(node.right != null){
nodeList.add(node.right);
}
}
return ret;
}
}