题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root==null)
return res;
queue.offer(root);
while(queue.isEmpty()!=true){
TreeNode tmp = queue.poll();
res.add(tmp.val);
if(tmp.left!=null)
queue.offer(tmp.left);
if(tmp.right!=null)
queue.offer(tmp.right);
}
return res;
}
}
要注意Java在OJ上的包比较麻烦。
Java 中Queue是一个接口,实现由LinkedList实现
API使用offer和poll
注意判断子树是否为空