平衡二叉树问题,本题考察的知识点有,平衡二叉树的生成,左旋,右旋,如何判断一个树是否是完全二叉树,二叉树的层序遍历。 坑点如下 1,将左旋函数和右旋函数写反了导致段错误。 整体代码如下
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct Node{
int data,height;
Node* lchild;
Node* rchild;
};
Node* newnode(int v){
Node* root=new Node;
root->height=1;
root->data=v;
root->lchild=root->rchild=NULL;
return root;
}
int getheight(Node* root){
if(root==NULL)return 0;
return root->height;
}
int getbalancef(Node* root){
return getheight(root->lchild)-getheight(root->rchild);
}
void r(Node* &root){
Node* temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
root->height= max(getheight(root->lchild),getheight(root->rchild))+1;
temp->height= max(getheight(temp->lchild),getheight(temp->rchild))+1;
root=temp;
}
void l(Node* &root){
Node* temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
root->height= max(getheight(root->lchild),getheight(root->rchild))+1;
temp->height= max(getheight(temp->lchild),getheight(temp->rchild))+1;
root=temp;
}
void insert(Node* &root,int data){
if(root==NULL){
root=newnode(data);
return;
}
if(data<root->data){
insert(root->lchild,data);
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
if(getbalancef(root)==2){
if(getbalancef(root->lchild)==1)
{
r(root);
}
else if(getbalancef(root->lchild)==-1)
{ l(root->lchild);
r(root);
}
}
}
else
{ insert(root->rchild,data);
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
if(getbalancef(root)==-2){
if(getbalancef(root->rchild)==-1)
{ l(root);
}
else if(getbalancef(root->rchild)==1)
{ r(root->rchild);
l(root);
}
}
}
}
int maxnow=-1;
void DFS(Node* &root,int index){
if(index>maxnow)maxnow=index;
if(root->lchild!=NULL)DFS(root->lchild,index*2);
if(root->rchild!=NULL) DFS(root->rchild,index*2+1);
}
int main(){
int n,data;
scanf("%d",&n);
Node* root=NULL;
for(int i=0;i<n;i++){
scanf("%d",&data);
insert(root,data);
}
DFS(root,1);
int cnt=0;
queue<Node*>Q;
Q.push(root);
while(!Q.empty()){
Node* node=Q.front();
Q.pop();
printf("%d",node->data);
cnt++;
if(cnt<n)printf(" ");
if(node->lchild!=NULL)Q.push(node->lchild);
if(node->rchild!=NULL)Q.push(node->rchild);
}
printf("\n");
printf("%s\n",maxnow==n?"YES":"NO");
return 0;
}
|