[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;
    }
};
原文地址:https://www.cnblogs.com/hellojamest/p/12245765.html