课后习题一共四道代码题,下面分别给出代码,但是没有测试.
1.判断二叉树是否是二叉排序树
int judBST(BTNode *bt){
int b1,b2;
if(bt==NULL){
return 1;
}
else{
b1 = judBST(bt->left);
if(b1 == 0 || predt>bt->value)
{
return 0;
}
predt = bt->value;
b2 = judBST(bt->right);
return b2;
}
}
主要思想是看中序递增
2.确定平衡二叉树第k个结点的位置
它增加了一个域
typedef struct BTNode{
int value;
BTNode*left,*right;
int lsize;
int count;
}BTNode;
BTNode *search_small(BTNode *t,int k){
if(t== NULL || k<1){
return NULL;
}
if(t->lsize == k)
return t;
if(t->lsize >k){
return search_small(t->left,k);
}else{
return search_small(t->right,k-t->lsize);
}
}
3. 统计二叉排序树相同结点个数
这个用递推遍历,不停的跳来跳去而没有用栈
void insert(BTNode *&t,BTNode *&pr,int x){
BTNode *p = t;
while(p!=NULL){
if(p->value !=x){
pr = p;
if(x<p->value){
p = p->left;
}else
p = p->right;
}else{
++(p->count);
return ;
}
}
BTNode *s = (BTNode *)malloc(sizeof(BTNode));
s->value = x;
s->count = 1;
s->left = s->right = NULL;
if(pr==NULL)
t = s;
else if(x<pr->value)
pr->left = s;
else pr->right = s;
}
4.给定关键值序列是否是二叉排序树查找序列.
这个是分两个左右序列。
typedef struct{
int elem[12];
int len;
}Sequence;
void reduce(Sequence &S,Sequence &S1,Sequence &S2){
int i = 0,j = 0,k = 0;
do{
while(i+1 < S.len && S.elem[i]<S.elem[i+1])
S1.elem[j++] = S.elem[i++];
while(i+1 < S.len && S.elem[i] > S.elem[i+1])
S2.elem[k++] = S.elem[i++];
}while(i+1<S.len);
S1.len = j;
S2.len = k;
}
int judge(Sequence &S1,Sequence &S2,int x){
int i,flag ;
flag = 1;
i = 0;
while(flag && i+1<S1.len)
if(S1.elem[i] > S1.elem[i+1] || S1.elem[i] > x)
flag = 0;
else
++i;
i = 0;
while(flag && i+1<S2.len)
if(S2.elem[i] < S2.elem[i+1] || S2.elem[i] < x)
flag = 0;
else
++i;
return flag;
}
int issearch(Sequence &S,Sequence &S1,Sequence &S2,int x){
reduce(S,S1,S2);
return judge(S1,S2,x);
}