题目
为什么不会爆ll呢,因为节点个数有限,深度有限,假如很稀疏的话,会导致层数很多,但是稀疏的话在bfs过程中就会判断出不是完全二叉了。
class Solution {
#define pi pair<TreeNode*,int>
public:
bool isCompleteTree(TreeNode* root) {
if(!root) return true;
queue<pi>q;q.push(make_pair(root,1));
int sz=1;
while(!q.empty()){
pi cur=q.front();q.pop();
TreeNode *x=cur.first;int y=cur.second;
if(x->left){
q.push(make_pair(x->left,y<<1)),++sz;
if(sz<y*2) return false;//!一定要判断 比如[1,2,3,5,null,7];
}
if(x->right){
q.push(make_pair(x->right,y<<1|1)),++sz;
if(sz<y*2+1) return false;
}
}
return true;
}
};
class Solution {
public:
struct node{
int flag,dep;
};
node wc(TreeNode *root){
if(root==NULL) return (node){1,0};
node x=wc(root->left),y=wc(root->right);
if(!(x.flag!=-1&&y.flag!=-1)) return (node){-1,0};
if(x.dep==y.dep){//深度相同
if(x.flag!=1) return (node){-1,0};//左边不是满二叉
if(y.flag!=1) return (node){0,x.dep+1};//以root为根的树为完全二叉,但不是满二叉
return (node){1,x.dep+1};//以root为根的树为满二叉
}else{//深度不同要求 右边为满二叉且左边深度-右边深度=1
if(y.flag!=1||!(x.dep-y.dep==1)) return (node){-1,0};//非完全二叉
return (node){0,x.dep+1};//非满二叉
}
}
bool isCompleteTree(TreeNode* root) {
return wc(root).flag!=-1?true:false;
}
};