面试题32(剑指offer)--从上到下打印二叉树

本文深入探讨了二叉树的两种打印算法:按层顺序打印和之字形打印。详细介绍了算法思路与实现代码,适合对数据结构与算法有兴趣的学习者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目一:

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印 ,每一层打印一行

思路:

使用变量记录第几行有几个节点要打印,toBePrinted记录该行要打印的节点数量,nextLevel统计下一行要打印的节点数。

代码:

	/**
     * 分行从上到下打印
     * @param node
     */
    private static void Print(BinaryTreeNode node){
        if (node==null){
            return;
        }
        LinkedList<BinaryTreeNode> list=new LinkedList<>();
        list.offer(node);
        int nextLevel=0;
        int toBePrinted=1;
        while (!list.isEmpty()){
            BinaryTreeNode temp=list.poll();
            print(temp);
            if (temp.left!=null){
                list.offer(temp.left);
                nextLevel++;
            }
            if (temp.right!=null){
                list.offer(temp.right);
                nextLevel++;
            }
            toBePrinted--;
            if (toBePrinted==0){
                System.out.println();
                toBePrinted=nextLevel;
                nextLevel=0;
            }
        }
    }
	private static void print(BinaryTreeNode node){
        System.out.print(node.val+"\t");
    }

题目二:

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他以此类推。

思路:

用两个栈实现,一个栈先进左孩子,再进右孩子,另一个栈与之相反,一个栈存储一行的元素。

代码:

	/**
     * 之字形打印
     * @param node
     */
    private static void PrintCyc(BinaryTreeNode node){
        if (node==null){
            return;
        }
        Stack<BinaryTreeNode> stack1=new Stack<>();
        Stack<BinaryTreeNode> stack2=new Stack<>();
        stack1.push(node);
        while (!stack1.empty()||!stack2.empty()){
            if (stack2.empty()){
                while (!stack1.empty()){
                    BinaryTreeNode tmp=stack1.pop();
                    print(tmp);
                    if (tmp.left!=null){
                        stack2.push(tmp.left);
                    }
                    if (tmp.right!=null){
                        stack2.push(tmp.right);
                    }
                }
                System.out.println();
            }else {
                while (!stack2.empty()){
                    BinaryTreeNode tmp=stack2.pop();
                    print(tmp);
                    if (tmp.right!=null){
                        stack1.push(tmp.right);
                    }
                    if (tmp.left!=null){
                        stack1.push(tmp.left);
                    }
                }
                System.out.println();
            }
        }
    }
    private static void print(BinaryTreeNode node){
        System.out.print(node.val+"\t");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值