题目描述: 从上往下打印出二叉树的每个节点,同层节点从左至右打印(二叉树层次遍历)
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if(root == null)
return res;
//Queue is abstract; 不能用 new Queue<TreeNode>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(queue.size()!=0){
root=queue.remove();
res.add(root.val);
if(root.left!=null){
queue.add(root.left);
}
if(root.right!=null){
queue.add(root.right);
}
}
return res;
}
}