题干
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
从上到下打印二叉树就是层序遍历,这里可以借鉴我之前写过的博文二叉树的遍历
代码
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<TreeNode>();
ArrayList<Integer> array=new ArrayList<Integer>();
if(root==null)return array;
queue.offer(root);
// array.add(root.val); 如何进行表示表示他们是在同一层 是个问题的关键所在 可以利用for循环来实现判断是否还存在数据供我们访问,是一个经典所在。
while(queue.size()!=0){
int len=queue.size();
for(int i=0;i<len;i++){
TreeNode temp=queue.poll();
if(temp.left!=null){
queue.add(temp.left);
}
if(temp.right!=null){
queue.add(temp.right);
}
array.add(temp.val);
}
}
return array;
}
}