从上往下打印出二叉树的每个节点,同层节点从左至右打印
import java.util.ArrayList;
import java.util.LinkedList;
/**
public 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) {
//定义一个辅助队列
LinkedList<TreeNode> queue=new LinkedList<>();
//存储一层的打印结果
ArrayList<Integer> resultCur=new ArrayList<Integer>();
//存储所有的打印结果
//ArrayList<ArrayList<Integer>> result=new ArrayList<>();
if(root==null){
return resultCur;
}
//定义两个变量last和nlast,分别记录当前行的最右节点和下一行的最右节点
TreeNode last=root;
TreeNode nlast=root;
TreeNode cur=root;
queue.add(root);
while(queue.size()!=0){
cur=queue.poll();
resultCur.add(cur.val);
if(cur.left!=null){
queue.add(cur.left);
nlast=cur.left;
}
if(cur.right!=null){
queue.add(cur.right);
nlast=cur.right;
}
if(cur==last){
//result.add(resultCur);
// resultCur=new ArrayList<>();
last=nlast;
}
}
return resultCur;
}
}