/**
* 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;
vector<TreeNode*> node;
vector<int> layernum;
vector<int> pos;
vector<int> Front,Back;
int front=0;
node.push_back(root);
layernum.push_back(0);
pos.push_back(1);
Front.push_back(1);
while(node.size()-front>0){
if(front!=0&&layernum[front]!=layernum[front-1]){
Back.push_back(pos[front-1]);
Front.push_back(pos[front]);
}
if(node[front]->left!=NULL){
node.push_back(node[front]->left);
layernum.push_back(layernum[front]+1);
pos.push_back(pos[front]*2);
}
if(node[front]->right!=NULL){
node.push_back(node[front]->right);
layernum.push_back(layernum[front]+1);
pos.push_back(pos[front]*2+1);
}
front++;
}
Back.push_back(pos[front-1]);
int max;
max=Back[0]-Front[0]+1;
for(int i=0;i<Front.size();i++){
max=max>Back[i]-Front[i]+1?max:Back[i]-Front[i]+1;
}
return max;
}
};