[Leetcode]662.Maximum Width of Binary Tree

链接:LeetCode662

给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。

每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。

相关标签:

这道题实际上是求每层节点最左边与右边的距离。这道题关键点在于,我们需要知道,对于一颗满二叉树,节点n的左右节点分别是2n(2n+1)。知道这点后,我们利用一个队列,通过求层遍历的方式即可得每一层宽度。

代码如下:

python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def widthOfBinaryTree(self, root: TreeNode) -> int:
        res = 0
        if not root:
            return res
        queue = collections.deque()
        queue.append([root,1])
        while queue:
            left_ind = queue[0][-1]
            for _ in range(len(queue)):
                q,ind = queue.popleft()
                if q.left:
                    queue.append([q.left,ind*2])
                if q.right:
                    queue.append([q.right,ind*2+1])
            res = max(res,ind-left_ind+1)
        return res

C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        int res = 0;
        if(!root) return res;
        queue<pair<TreeNode*,double>> q;
        q.push({root,1});
        while(!q.empty()){
            double left = q.front().second,right=0,n = q.size();
            for(int i=0;i<n;++i){
                TreeNode* treeNode = q.front().first;
                right = q.front().second;
                q.pop();
                if(treeNode->left) q.push({treeNode->left,right*2});
                if(treeNode->right) q.push({treeNode->right,right*2+1});
            }
            res = max(res,(int)(right-left+1));
        }
        return res;
    }
};
posted @   Jamest  阅读(158)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示