题目描述
解题思路:
思路是用arraylist模拟一个队列来存储相应的TreeNode
代码如下:
import java.util.ArrayList;
import java.util.List;
/**
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> list = new ArrayList<>();
ArrayList<TreeNode> queue = new ArrayList<>();
if (root == null) {
return list;
}
queue.add(root);//先让根节点进队列
while (queue.size() != 0) {
TreeNode temp = queue.remove(0);//让队列中的第一个节点出队列
if (temp.left != null){
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
list.add(temp.val);
}
return list;
}
}