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
這道題的意思是:給一個(gè)有著滿二叉樹結(jié)構(gòu)照激,但是有部分節(jié)點(diǎn)是null的樹,然后求出這個(gè)樹最寬的那一層的寬度。這個(gè)寬度就是每一層的最右和最左的距離的最大值。看起來不是很難做,有一個(gè)很暴力的方法就是把一層的節(jié)點(diǎn)都保存下來不管空不空,然后一個(gè)一個(gè)去遍歷找到最左和最右的下標(biāo)批销。但是我們作為一個(gè)coder洒闸,這么蠢的方法還是少用。這里要用到樹的一個(gè)特點(diǎn)均芽。每個(gè)節(jié)點(diǎn)的下標(biāo)如果是i丘逸,那么它的左節(jié)點(diǎn)是 2 * i, 右節(jié)點(diǎn)是 2 * i + 1。然后掀宋,我們只要將每個(gè)節(jié)點(diǎn)和它的位置保存下來深纲,做層序遍歷。開始一層的遍歷時(shí)劲妙,定義一個(gè)最左和一個(gè)最右的變量湃鹊,將這層第一個(gè)節(jié)點(diǎn)的位置保存下來,然后每遍歷這層的一個(gè)節(jié)點(diǎn)镣奋,將該節(jié)點(diǎn)的位置更新為最右變量的值币呵。這一層遍歷完后就可以得到這層的寬度,然后跟當(dāng)前最大的寬度比較侨颈,然后更新最大值即可余赢。
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;
}
};