6-6 CheckBST[1] (30 分)
Sample Input 1: (for the following tree)
4
Sample Output 1:
Yes. Key = 5
Sample Input 2: (for the following tree)
3
Sample Output 2:
No. Height = 3
誤區:判斷BST要用中序遍歷,看是否遞增。
而不能遍歷每個節點,判斷其左右節點是否滿足。
1、二叉排序樹的定義
二叉排序樹(Binary Sort Tree)又稱二叉查找(搜索)樹(Binary Search Tree)。
其定義爲:
二叉排序樹或者是空樹,或者是滿足如下性質的二叉樹:
①若它的左子樹非空,則左子樹上所有結點的值均小於根結點的值;
②若它的右子樹非空,則右子樹上所有結點的值均大於根結點的值;
③左、右子樹本身又各是一棵二叉排序樹。
之前寫的
//wrong,judge bst fail
//24分,一個點過不去(判斷bst)
//模擬數組bfs,用struct存所有節點,判斷最大depth,排序節點,獲得K-th max;
struct q {
BinTree Te;
int dep;
}q[1000];
int cmp(const void* a,const void* b) {
return (*(struct q*)a).Te->Key < (*(struct q*)b).Te->Key;
}
int CheckBST(BinTree T, int K) {
int sor[1000];int i = 0;
int max = 0;
int rear, head;
head = rear = 0;
BinTree t = T;
struct q x;x.Te = t;x.dep = 1;
q[rear++] = x;int checkbst = 0;
while (rear - head > 0) {
struct q tem = q[head++];
sor[i++] = tem.Te->Key;
if (tem.dep > max)
max = tem.dep;
if (tem.Te->Left) {
if (tem.Te->Left->Key >= tem.Te->Key)
checkbst++;//錯誤判斷
struct q i;i.Te = tem.Te->Left;i.dep = tem.dep + 1;
q[rear++] = i;
}
if (tem.Te->Right) {
if (tem.Te->Right->Key <= tem.Te->Key)
checkbst++;//錯誤
struct q i;i.Te = tem.Te->Right;i.dep = tem.dep + 1;
q[rear++] = i;
}
}
if (checkbst) {
return -max;
}
else {
qsort(q, rear, sizeof(struct q), cmp);
return q[K - 1].Te->Key;
}
}
太過繁瑣,無奈上網學習一下。
參考資料:https://blog.csdn.net/zxzxzx0119/article/details/81112061
https://www.cnblogs.com/edisonchou/p/4823213.html
最後寫的ac代碼
int dep(BinTree T) {
if (!T)
return 0;
int DL = dep(T->Left);
int DR = dep(T->Right);
return (DL > DR) ? DL + 1 : DR + 1;
}
int CheckBST(BinTree T, int K) {
int depth = dep(T);
BinTree stack[1000];int sor[1000];
sor[0] = -0x3f3f3f;
int top = 0;int i = 1;
BinTree cur = T;
while (top || cur) {
if (cur) {
stack[top++] = cur;
cur = cur->Left;
}
else {
cur = stack[top - 1];
if (cur->Key < sor[i - 1])
return -depth;
sor[i++] = stack[--top]->Key;
cur = cur->Right;
}
}
return sor[i - K];
}