LeetCode 第 662 题:二叉树最大宽度

1、前言

题目描述

2、思路

利用满二叉树的性质来解题,如果 root 的索引为 i,则它的左孩子为 i * 2,右孩子为 i * 2 + 1。

3、代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        int max = 0;
        root.val = 1;
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            int start = queue.peek().val;
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    node.left.val = node.val * 2;
                    queue.offer(node.left);
                }
                if(node.right != null){
                    node.right.val = node.val * 2 + 1;
                    queue.offer(node.right);
                }
                if(i == size - 1){
                    max = Math.max(max, node.val - start + 1);
                }
            }
        }
        
        return max;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容