版权声明:while (!success) try(); https://blog.csdn.net/qq_35850147/article/details/88960360
6-5 CheckBST[1] (30 分)
Given a binary tree, you are supposed to tell if it is a binary search tree. If the answer is yes, try to find the K-th largest key, else try to find the height of the tree.
Format of function:
int CheckBST ( BinTree T, int K );
where BinTree
is defined as the following:
typedef struct TNode *BinTree;
struct TNode{
int Key;
BinTree Left;
BinTree Right;
};
The function CheckBST
is supposed to return the K
-th largest key if T
is a binary search tree; or if not, return the negative height of T
(for example, if the height is 5, you must return −5).
Here the height of a leaf node is defined to be 1. T
is not empty and all its keys are positive integers. K
is positive and is never more than the total number of nodes in the tree.
Sample program of judge:
#include <stdio.h>
#include <stdlib.h>
typedef struct TNode *BinTree;
struct TNode{
int Key;
BinTree Left;
BinTree Right;
};
BinTree BuildTree(); /* details omitted */
int CheckBST ( BinTree T, int K );
int main()
{
BinTree T;
int K, out;
T = BuildTree();
scanf("%d", &K);
out = CheckBST(T, K);
if ( out < 0 )
printf("No. Height = %d\n", -out);
else
printf("Yes. Key = %d\n", out);
return 0;
}
/* 你的代码将被嵌在这里 */
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
题解:
int maxh, cnt, v[1000];
void mid(BinTree t, int h)
{
maxh = h > maxh ? h : maxh;
if (t->Left)
mid(t->Left, h + 1);
v[cnt++] = t->Key;
if (t->Right)
mid(t->Right, h + 1);
return;
}
int CheckBST(BinTree T, int K)
{
mid(T, 1);
for (int i = 1; i < cnt; i++)
if (v[i] < v[i - 1])
return -maxh;
return v[cnt - K];
}
#include <stdbool.h>
int cmp(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
}
int CheckBST(BinTree T, int K)
{
bool BST = true, flag = true;
int vcnt = 0, lcnt = 0, mdep = 1, v[1000] = {0};
BinTree List[1000] = {NULL}, pre[1000] = {NULL};
List[lcnt++] = T;
pre[T->Key] = T;
while (flag)
{
flag = false;
BinTree t = NULL;
for (int i = 0; i < lcnt; i++)
{
if (List[i])
{
flag = true;
t = List[i];
v[vcnt++] = t->Key;
List[i] = NULL;
break;
}
}
if (t)
{
if (!t->Left && !t->Right)
{
int k = t->Key, dep = 1;
while (pre[k]->Key != k)
{
dep++;
k = pre[k]->Key;
}
if (dep > mdep)
mdep = dep;
}
if (t->Left)
{
List[lcnt++] = t->Left;
pre[t->Left->Key] = t;
if (t->Key < t->Left->Key || (pre[t->Key]->Right == t && pre[t->Key]->Key > t->Left->Key))
BST = false;
}
if (t->Right)
{
List[lcnt++] = t->Right;
pre[t->Right->Key] = t;
if (t->Key > t->Right->Key || (pre[t->Key]->Left == t && pre[t->Key]->Key < t->Right->Key))
BST = false;
}
}
}
qsort(v, vcnt, sizeof(int), cmp);
return BST ? v[K - 1] : -mdep;
}