二叉树按层打印,求最大的宽度

14 篇文章 0 订阅

一.按层打印,从左到右分层打印

    public static void level(Node node) {

        if (node != null) {
            Queue<Node> queue = new LinkedList<Node>();
            queue.add(node);
            while (!queue.isEmpty()) {
                Node n=queue.poll();
                System.out.print (n.val+" ");
                if(n.leftChild!=null){
                    queue.add(n.leftChild);
                }
                if(n.rightChild!=null){
                    queue.add(n.rightChild);
                }

            }
        }
    }

二. 求二叉树最大的宽度(哪一次节点最多)

最重要的是找到每一次最右的那个节点,这样跟弹出的结点来比较,就能确定这一层已经遍历完成,一共有多少个节点了

public static int levelWidth(Node node) {

        if (node == null) {
            return 0;
        }

        Queue<Node> queue = new LinkedList<Node>();
        queue.add(node);
        int max = 0;
        int currentLevelNodes = 0;//当前层的节点数
        Node nextRightNode = null;//下一层最右节点
        Node currentLevelRightNode = node;//当前层最右节点
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.leftChild != null) {
                queue.add(cur.leftChild);
                nextRightNode = cur.leftChild;
            }
            if (cur.rightChild != null) {
                queue.add(cur.rightChild);
                nextRightNode = cur.rightChild;
            }
            currentLevelNodes++;
            //当前弹出的结点如果是当前层最右的结点,
            // 说明该层的所有结点都已经弹出,要遍历下一层了
            if (cur == currentLevelRightNode) {
                max = Math.max(max, currentLevelNodes);
                currentLevelNodes = 0;
                //设置下一层最右的结点(核心逻辑)
                // 这样在遍历下一层时就知道最右的边界了
                currentLevelRightNode = nextRightNode;
            }

        }
        System.out.println();
        return max;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值