和答案不太一样,不知道写的对不对。反正也没几个,想了想写下来记录一下。
//判断是否为二叉排序树
bool judgeBST(BinNode* cur) {
bool l,r; //左右子树结果
if(cur==NULL) return 1; //空结点返回1
l=judgeBST(cur->left()); //检查左子树
if(!l||pre>=cur->getValue()) return 0; //左子树非BST或树非中序有序
pre=cur->getValue(); //重新set前驱值
r=judgeBST(cur->right()); //检查右子树
return r; //真假与右子树一致
}
//查找dest结点在BST中的层数
int level(BinNode* dest,BinBode cur) {
BinNode* p=cur;
int n=0;
if(cur==NULL) return 0;
n++;
while(p->getValue()!=dest->getValue()) {
if(p->getValue()<dest->getValue()) p=p->right();
else p=p->left();
n++;
}
return n;
}
//检查是否为AVL
void judgeAVL(BinNode* r,int &balance,int &h) {
int l,r,hl,hr;//左右平衡标记和高度
if(r==NULL) {h=0;balance=1;} //空树,高度为0
else if(r->isleaf()) { //叶子结点
h=1;
balance=1;
}
else{
judgeAVL(r->left(),l,hl); //递归判断左子树
judgeAVL(r->right(),r,hr); //递归判断左子树
h=(hl>hr?hl:hr)+1;
if(abs(hl-hr)<2) balance=l&&r;
else balance=0;
}
}
//重头戏来了,在以t为根的子树上寻找第k小的元素,返回其所在结点的指针
//count保存以该结点为根的子树的结点个数
//这个算法没有见过,只能说缘,妙不可言
BinNode* search_small(BSTNode* t,int k) {
if(k<1||k>t->count) return NULL; //k值不合法
if(t->left==NULL) { //只有右子树,疑似目标值
if(k==1) return t;
else return search_small(t->right,k-1);
}
else {
if(t->left->count==k-1) return t; //左子树上结点个数恰为k-1
if(t->left->count>k-1) return searchsmall(t->left,k);
if(t->left->count<k-1) return searchsmall(t->right,k-(t->left->count+1));
}
}