第一题 从上往下打印二叉树
按层打印二叉树过程: 解题思路参考 http://blog.sina.com.cn/s/blog_a1ce3d4b0102wj44.html
https://blog.csdn.net/lilianforever/article/details/51851357
借助先入先出的队列(特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作)
队列获取头结点后,先弹出头结点,如果有左树将左树压入队列,有右树也压入队列,打印当前头结点。循环检查队列是否为空队列,然后处理
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<Integer>();
if``(root==``null``){
return
list;
}
Queue<TreeNode> queue =
new
LinkedList<TreeNode>();
queue.offer(root);
while
(!queue.isEmpty()) {
TreeNode treeNode = queue.poll();
if
(treeNode.left !=
null``) {
queue.offer(treeNode.left);
}
if
(treeNode.right !=
null``) {
queue.offer(treeNode.right);
}
list.add(treeNode.val);
}
return
list;
}
}