-
Notifications
You must be signed in to change notification settings - Fork 7
/
4-5-8.cpp
78 lines (78 loc) · 1.69 KB
/
4-5-8.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<iostream>
using namespace std;
#define ELEMTYPE int
#define MAXSIZE 50
#define END 9999
typedef struct BNode{
struct BNode* lchild;
struct BNode* rchild;
ELEMTYPE key;
int count;
}BNode,*BST;
bool flag=true;
int fun(BST T){
if(T){
int h1,h2;
h1=fun(T->lchild);
h2=fun(T->rchild);
if(abs(h1-h2)>1)flag=false;
return max(h1,h2)+1;
}
return 0;
}
bool BST_Insert(BST &T,ELEMTYPE x);
void InitBST(BST &T,ELEMTYPE L[]);
void Print_BST(BST T,int tag);
BST BST_search(BST T,ELEMTYPE value);
int main(){
ELEMTYPE L[MAXSIZE];
ELEMTYPE c;
cin>>c;
int i=0;
for(i=0;i<MAXSIZE&&c!=END;i++){
L[i]=c;
cin>>c;
}
L[i]=c;
BST T=NULL;
InitBST(T,L);
fun(T);
cout<<(flag?"true":"false")<<endl;
Print_BST(T,2);
cout<<endl;
return 0;
}
BST BST_search(BST T,ELEMTYPE value){
if(!T)return NULL;
if(T->key>value)return BST_search(T->lchild,value);
else if(T->key<value)return BST_search(T->rchild,value);
else return T;
return NULL;
}
bool BST_Insert(BST &T,ELEMTYPE x){
if(T){
if(x<T->key)return BST_Insert(T->lchild,x);
else if(x>T->key)return BST_Insert(T->rchild,x);
else return false;
}else{
T=(BST)malloc(sizeof(BNode));
T->key=x;
T->lchild=NULL;
T->rchild=NULL;
return true;
}
}
void InitBST(BST &T,ELEMTYPE L[]){
for(int i=0;L[i]!=END;i++){
BST_Insert(T,L[i]);
}
}
void Print_BST(BST T,int tag){
if(!T)return ;
if(tag==1)cout<<T->key<<" ";
Print_BST(T->lchild,tag);
if(tag==2)cout<<T->key<<" ";
Print_BST(T->rchild,tag);
if(tag==3)cout<<T->key<<" ";
free(T);
}