37:从上到下打印二叉树

从上到下打印二叉树

二叉树的层次遍历的变种,使用两个变量记录待打印的数据个数和下次待打印的数据个数即可。

public class Offer37 {

    public static void cengci2(TreeNode root){
        if(root==null)return;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        Integer nextLevel = 0;
        int toBePrint = 1;
        while (!queue.isEmpty()){
            TreeNode remove = queue.removeFirst();
            System.out.print(remove.value+" ");
            toBePrint--;
            if(remove.left!=null) {
                queue.add(remove.left);
                nextLevel++;
            }
            if(remove.right!=null) {
                queue.add(remove.right);
                nextLevel++;
            }
            if(toBePrint==0){
                System.out.println();
                toBePrint = nextLevel;
                nextLevel=0;
            }
        }
    }

    public static void main(String[] args) {
        TreeNode root = Main.createNode();
        cengci2(root);
    }

}

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页