题目:
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));
}
};