7-3 Is It An AVL Tree (25 分)
In computer science, an AVL tree (Georgy Adelson-Velsky and Evgenii Landis’ tree, named after the inventors) is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one. (Quoted from wikipedia) For each given binary search tree, you are supposed to tell if it is an AVL tree.
Input Specification:
Each input file contains several test cases. The first line gives a positive integer K (≤10) which is the total number of cases. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary search tree. The second line gives the preorder traversal sequence of the tree with all the keys being distinct. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in a line “Yes” if the given tree is an AVL tree, or “No” if not.
Sample Input:
3
7
50 40 36 48 46 62 77
8
50 40 36 48 46 62 77 88
6
50 40 36 48 46 62
Sample Output:
Yes
No
No
分析:给出二叉查找树的先序序列,判断是否为avl树
解决:先序+中序建树,先序遍历赋高度,再遍历判断每个结点的左右子树的最大高度差,大于1则不是AVL树。
错误点:
1、while(in[k]!=pre[prel]) k++;不能写成while(in[k++]!=pre[prel]);
2、sort(in,in+m);不能写成sort(in,in+m-1);
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
struct node{
int v,height,tag;
node *lchild,*rchild;
};
int pre[35] = {0},in[35]={0};
node* creat(int prel,int prer,int inl,int inr){
if(prel>prer) return NULL;
node* root = new node;
root->v = pre[prel];
int k = inl;
while(in[k]!=pre[prel]) k++;
int numl = k-inl;
root->lchild = creat(prel+1,prel+numl,inl,inl+numl-1);
root->rchild = creat(prel+numl+1,prer,k+1,inr);
return root;
}
void dfs(node* &root,int deep){
if(root==NULL) return;
root->height = deep;
//cout<<root->v<<" "<<deep<<endl;
dfs(root->lchild,deep+1);
dfs(root->rchild,deep+1);
}
void getmaxheight(node* root,int &maxdeep){
if(root->height >= maxdeep) maxdeep = root->height;
if(root->lchild !=NULL) getmaxheight(root->lchild,maxdeep);
if(root->rchild !=NULL) getmaxheight(root->rchild,maxdeep);
}
void judge(node* root,bool &flag){
int ldeep = root->height,rdeep = root->height;
if(root->lchild !=NULL) getmaxheight(root->lchild,ldeep);
if(root->rchild !=NULL) getmaxheight(root->rchild,rdeep);
if(abs(ldeep-rdeep)>1) {
flag = false;
return;
}
if(root->lchild !=NULL) judge(root->lchild,flag);
if(root->rchild !=NULL) judge(root->rchild,flag);
}
int main() {
int n,m;
cin>>n;
while(n--){
cin>>m;
for(int i=0;i<m;i++){
cin>>pre[i];
in[i] = pre[i];
}
sort(in,in+m);
node* root = creat(0,m-1,0,m-1);
dfs(root,1);/**/
bool flag = true;
judge(root,flag);
if(flag) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}