目的:构建AVL树,然后判断是否是完全二叉树
输入:
一串节点序列
输出:
层序序列
以及判断是否是满二叉树
#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;
struct node{
int val,height;
node* left,*right;
};
node* newnode(int v)
{
node* now = new node;
now->height = 1;
now->val = v;
now->left = NULL;
now->right= NULL;
return now;
}
int getheight(node* root)
{
if(root==NULL) return 0;
return root->height;
}
int getbalancefactor(node* root)
{
//获得左右子树的高度差
return getheight(root->left)-getheight(root->right);
}
void updateheight(node* root)
{
root->height = max(getheight(root->left),getheight(root->right))+1;//要是和getheight互换,那么每次查询高度差都要计算,可能会超时。更新计算
}
void L(node* &root)
{
node* temp = root->right;
root->right = temp->left;
temp->left = root;
updateheight(root);
updateheight(temp);
root = temp;
}
void R(node* &root)
{
node* temp = root->left;
root->left = temp->right;
temp->right= root;
updateheight(root);
updateheight(temp);
root = temp;
}
void insert(node* &root,int x)
{
if(root==NULL)
{
root = newnode(x);
return;
}
if(x < root->val)
{
insert(root->left,x);
updateheight(root);
if(getbalancefactor(root)==2)
{
if(getbalancefactor(root->left)==1)
{
R(root);
}else
{
L(root->left);
R(root);
}
}
}else{
insert(root->right,x);
updateheight(root);
if(getbalancefactor(root)==-2)
{
if(getbalancefactor(root->right)==-1)
{
L(root);
}else
{
R(root->right);
L(root);
}
}
}
}
bool BFS(node* root)
{
bool flag = true;
int tag = 0;
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* top = q.front();
printf("%d",top->val);
q.pop();
if(top->left!=NULL)
{
q.push(top->left);
if(tag==1)
{
flag = false;
}
}else
{
if(tag==0)
{
tag=1;
}
}
if(top->right!=NULL)
{
q.push(top->right);
if(tag==1)
{
flag = false;
}
}else
{
if(tag==0)
{
tag=1;
}
}
if(!q.empty())
{
printf(" ");
}else
{
printf("\n");
}
}
return flag;
}
int main()
{
int N;
scanf("%d",&N);
node* root = NULL;
for(int i=0;i<N;i++)
{
int x;
scanf("%d",&x);
insert(root,x);
}
if(BFS(root))
{
printf("YES\n");
}else
{
printf("NO\n");
}
return 0;
}
反思:忘记了AVL怎么建树了。