/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int widthOfBinaryTree(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> qu; //记录结点
queue<int> order; //记录序号
qu.push(root);
order.push(1);
int maxwidth = 0,pos,first;
while(!qu.empty()){
int size = qu.size();
for(int i = 0;i < size;++i){
TreeNode *cur = qu.front();
pos = order.front();
if(i == 0)
first = pos;
if(i == size - 1)
maxwidth = max(maxwidth,pos - first + 1);
order.pop();
qu.pop();
if(cur->left){
qu.push(cur->left);
order.push(pos * 2);
}
if(cur->right){
qu.push(cur->right);
order.push(pos * 2 + 1);
}
}
}
return maxwidth;
}
};