Description
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.
Explain
這道題的意思是:給一個有著滿二叉樹結構,但是有部分節點是null的樹,然后求出這個樹最寬的那一層的寬度。這個寬度就是每一層的最右和最左的距離的最大值。看起來不是很難做,有一個很暴力的方法就是把一層的節點都保存下來不管空不空,然后一個一個去遍歷找到最左和最右的下標。但是我們作為一個coder,這么蠢的方法還是少用。這里要用到樹的一個特點。每個節點的下標如果是i,那么它的左節點是 2 * i, 右節點是 2 * i + 1。然后,我們只要將每個節點和它的位置保存下來,做層序遍歷。開始一層的遍歷時,定義一個最左和一個最右的變量,將這層第一個節點的位置保存下來,然后每遍歷這層的一個節點,將該節點的位置更新為最右變量的值。這一層遍歷完后就可以得到這層的寬度,然后跟當前最大的寬度比較,然后更新最大值即可。
Code
/**
* 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) {
if (!root) return 0;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
int max = INT_MIN;
while(!q.empty()) {
int size = q.size();
int start = 0;
int end;
for (int i = 0; i < size; i++) {
auto cur = q.front();
q.pop();
if (i == 0) {
start = cur.second;
}
end = cur.second;
if (cur.first->left) {
q.push(make_pair(cur.first->left, cur.second * 2));
}
if (cur.first->right) {
q.push(make_pair(cur.first->right, cur.second * 2 + 1));
}
}
max = max > (end - start + 1) ? max : end - start + 1;
}
return max;
}
};