LeetCode第662题二叉树最大宽度

题目描述

给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
在这里插入图片描述

解题思路

1、错误示例:没有认真审题,忽略了两端点间的null节点也计入长度这个条件,结果是错的,错误示例是采用非递归的层序遍历,取层数最大值,忽略有空节点这个条件。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            int width = 0;
            if(root == null) return width;
            queue.offer(root);
            while(!queue.isEmpty()){
                int size = queue.size();
                width = Math.max(width, size);
                while(size-- > 0){
                    TreeNode node = queue.poll();
                    if(node.left != null)
                        queue.offer(node.left);

                    if(node.right != null){
                        queue.offer(node.right);
                    }
                }
            }
            return width;
    }
}

在这里插入图片描述
2、更改:考虑到在这道题的结点值没有什么用,我们这里把变量val用来记录结点的索引值。
用到的知识点:
(1)对于任意结点的索引值为i, 其结点的左孩子的索引是2i,右孩子的索引是2i + 1
(2) peekFirst()表示列表的第一个元素(检索但不删除此列表的第一个元素,如果此列表为空,则返回null)
(3)peekLast() 表示列表的最后一个元素
注意

root.val = 0;
代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if(root == null) return 0;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        root.val = 0;
        int max = 1;
        while(!queue.isEmpty()){
            int size = queue.size();
            max = Math.max(max, queue.peekLast().val - queue.peekFirst().val + 1);
            for(int i = 0; i < size; i++){
                root = queue.poll();
                if(root.left != null){
                    root.left.val = root.val * 2;
                    queue.offer(root.left);
                }
                if(root.right != null){
                    root.right.val = root.val * 2 + 1;
                    queue.offer(root.right);
                }
            }
        }
        return max;
    }
}

参考:https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/106663/Java-O(n)-BFS-one-queue-clean-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值