剑指offer之 从上往下打印二叉树

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>();
        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){
                last=nlast;
            }
        }
        return resultCur;
    }
}

  

原文地址:https://www.cnblogs.com/toov5/p/7658422.html