LeetCode 662. 二叉树最大宽度
做题后的反思
这道题太恶心了,还要考虑数据范围溢出的问题。
同时通过做这道题我知道了c++中new 出来的结构体是一个指针类型的,要使用node *这种类型的对象来接收。同时,对于这种指针类型的我取值使用->,而不是点。
还有就是一般值与下标有关的我们做题时要考虑直接把值与标存放在一起,使用结构体或者pair,这样更加放标解题。
struct node{
TreeNode *t;
long long width;
node(TreeNode *_t,long long _width)
{
t=_t;
width=_width;
}
};
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<node *> q;
q.push(new node(root,1));
long long Max=-100000000000;
while(!q.empty())
{
node * l=q.front();
node * r=q.back();
Max=max((r->width - l->width)+1,Max);
int len=q.size();
long long start=l->width;
for(int i=0;i<len;i++)
{
node *a=q.front();
q.pop();
if(a->t->left) q.push(new node(a->t->left,(a->width-start+1)*2));
if(a->t->right) q.push(new node(a->t->right,(a->width-start+1)*2+1));
}
}
return Max;
}
};