[Leetcode] 662. Maximum Width of Binary Tree 解题报告

题目

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

Input: 

           1
         /   \
        3     2
       / \     \  
      5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: 

          1
         /  
        3    
       / \       
      5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: 

          1
         / \
        3   2 
       /        
      5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input: 

          1
         / \
        3   2
       /     \  
      5       9 
     /         \
    6           7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).


Note: Answer will in the range of 32-bit signed integer.

思路

我开始的时候把题意理解错了,结果怎么提交都不正确。后来才发现这里需要利用到满二叉树的性质:对于编号为i的一个节点,其左孩子和右孩子的编号为2*1和2*1 + 1。所以我们建立一个vec数组,用来存放每一层的最左边的节点的编号和最右边的节点的编号,这样每一层的宽度就可以由两者的差值得到。最后我们返回所有层中宽度最大者即可。

在实现中,对于当前节点,如果它到达了新的一层,我们就初始化该层的最左和最右节点编号,否则就更新最右节点编号(因为对于某一层而言,总是其最左边的节点被最先访问)。然后就计算当前层的宽度,并且递归计算它下面的孩子树的最大宽度,最后返回三者的最大值即可。

代码

/**
 * 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) {
        vector<pair<int, int>> vec;
        return dfs(root, 0, 1, vec);
    }
private:
    int dfs(TreeNode* root, int level, int order, vector<pair<int, int>>& vec){
        if(root == NULL) {
            return 0;
        }
        if(vec.size() == level) {
            vec.push_back({order, order});
        }
        else {
            vec[level].second = order;
        }
        int cur = vec[level].second - vec[level].first + 1;
        int left = dfs(root->left, level + 1, 2 * order, vec);
        int right = dfs(root->right, level + 1, 2 * order + 1, vec);
        return max(cur, max(left, right));
    }
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值