1101. Maximum Width of Binary Tree
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root
* @return: the maximum width of the given tree
*/
int widthOfBinaryTree(TreeNode * root) {
// Write your code here
// 類似與竖排的遍历
if(root == NULL){
return 0;
}
std::queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
int maxWidth = 1;
while(!q.empty()){
int sizeQ = q.size();
int left;
for(int i = 0; i < sizeQ; i++){
pair<TreeNode*, int> tmp = q.front();
q.pop();
if(i == 0){
left = tmp.second;
}
if(i == sizeQ - 1){
maxWidth = max(maxWidth, tmp.second - left + 1);
}
if(tmp.first->left){
q.push(make_pair(tmp.first->left, tmp.second * 2));
}
if(tmp.first->right){
q.push(make_pair(tmp.first->right, tmp.second * 2 + 1));
}
}
}
return maxWidth;
}
};
Comments
Post a Comment