30、从上到下打印二叉树——剑指offer

从上到下打印二叉树

问题描述:用一个队列放入要打印的节点指针,依次出队


    首先考察基本功,逻辑判断能力,栈的特性。

    本方法思想:用一个队列放入要打印的节点指针,依次出队,同时记录每一层有多少个数据


持续更新...

代码附下

Java实现:

package 层序遍历二叉树;
/**
 *层序遍历:用一个队列放入要打印的节点指针,依次出队
 * @author user
 *
 */

import java.util.LinkedList;
import java.util.Queue;
class BinaryTree {
    int val;
    BinaryTree left = null;
    BinaryTree right = null;
    public BinaryTree(int val) {
        this.val = val;
    }
}


public class Test {
    public static void main(String[] args) {
        BinaryTree rootA = new BinaryTree(8);
        rootA.left = new BinaryTree(8);
        rootA.right = new BinaryTree(7);
        rootA.left.left = new BinaryTree(9);
        rootA.left.right = new BinaryTree(2);
        rootA.left.right.left = new BinaryTree(4);
        rootA.left.right.right = new BinaryTree(7);
        printTop2Bottom(rootA);
    }


    public static void printTop2Bottom(BinaryTree root) {
        if (root == null) {
            return;
        }
        Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
        queue.add(root);
        int nextLevel = 0;// 下一层数目
        int toBePrint = 1;// 本层还要打印的数目
        while (!queue.isEmpty()) {
            BinaryTree temp = queue.poll();
            System.out.print(temp.val + " ");
            if (temp.left != null) {
                queue.add(temp.left);
                nextLevel++;
            }
            if (temp.right != null) {
                queue.add(temp.right);
                nextLevel++;
            }
            toBePrint--;
            if (toBePrint == 0) {
                System.out.println();
                toBePrint = nextLevel;
                nextLevel = 0;
            }
        }
    }
}

持续更新...欢迎赞赏!

主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008

如果有问题,欢迎大家留言,有更好的方法也期待大家告知。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值