【题目描述】从上往下打印出二叉树的每个节点,同层节点从左至右打印。
【简单思路】借助队列,画图看,先进先出。注意包位置。
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> re = new ArrayList<Integer>();
if (root==null){
return re;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty()) {
TreeNode cur = q.poll();
re.add(cur.val);
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
return re;
}
}