【二叉树】二叉树最大宽度

题目描述

给你一棵二叉树的根节点 root ,返回树的 最大宽度 。

树的 最大宽度 是所有层中最大的 宽度 。

每一层的 宽度 被定义为该层最左和最右的非空节点(即,两个端点)之间的长度。将这个二叉树视作与满二叉树结构相同,两端点间会出现一些延伸到这一层的 null 节点,这些 null 节点也计入长度。

示例1:

输入:root = [11,12,13,null,14]
输出:2
解释:最大宽度出现在树的第 2 层,宽度为 2 (12,13) 。

解题思路 

这道题其实是利用二叉树的性质,每一层的下标规则:左子树下标=父节点下标*2;右子树下标=父节点下标*2+1;如下图所示:

这里在原来树结构的基础上,增进position,用于记录每个节点的下标,整个类如下:

TreeNode

package org.example;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

TreeNodeExtend

 

class TreeNodeExtend {

    TreeNode node;
    int position;

    public TreeNodeExtend(TreeNode node, int position) {
        this.node = node;
        this.position = position;
    }
}

 

接着使用BFS进行遍历,这里我使用LinkedList模拟队列操作,具体代码实现如下:


import org.example.TreeNode;

import java.util.LinkedList;

class Solution {


    public int widthOfBinaryTree(TreeNode root) {

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

        LinkedList<TreeNodeExtend> deque = new LinkedList<>();
        deque.offer(new TreeNodeExtend(root, 0));

        int max = 1;

        while (!deque.isEmpty()) {

            max = Math.max(max, deque.get(deque.size() - 1).position - deque.get(0).position + 1);
            int sz = deque.size();
            for (int i = 0; i < sz; i++) {
                TreeNodeExtend node = deque.poll();

                if (node.node.left != null) {
                    deque.offer(new TreeNodeExtend(node.node.left, node.position * 2));
                }

                if (node.node.right != null) {
                    deque.offer(new TreeNodeExtend(node.node.right, node.position * 2 + 1));
                }
            }
        }
        return max;
    }

    class TreeNodeExtend {

        TreeNode node;
        int position;

        public TreeNodeExtend(TreeNode node, int position) {
            this.node = node;
            this.position = position;
        }
    }


}

 

总结

这道题就是2-3个简单问题组合到一起的中等难度问题;核心问题有:

  1. 二叉树的层序遍历,BFS;
  2. 二叉树的性质-下标生成的规则,并且构造有下标的二叉树;
  3. 最大值的获取。

这道题按照上述解法,耗时1ms左右。如果有更高效、更简洁的思路欢迎回复。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值