Given a binary search tree T, you are supposed to find the node with key value X, and return K if X is the K-th largest key.
Format of function:
int KthLargest ( BinTree T, int X );
where BinTree is defined as the following:
typedef struct TNode *BinTree;
struct TNode{
int Key;
BinTree Left;
BinTree Right;
};
Here T is not empty and all its keys are distinct positive integers. If X is not found, return 0 instead.
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 KthLargest ( BinTree T, int X );
int main()
{
BinTree T;
int X;
T = BuildTree();
scanf("%d", &X);
printf("%d", KthLargest(T, X));
return 0;
}
/* Your function will be put here */
Sample Input 1:
5
Sample Output 1:
4
Sample Input 2:
15
Sample Output 2:
0
Analysis:
用中序遍历得到序列,因为是二叉搜索树,则该序列一定是递增的,所以直接在序列中找输入的数,如果找到了直接返回(count-下标),count是序列的总数,因为序列从0开始;如果没找到直接返回0。
Notice:
- 如果不知道怎么用中序遍历得到序列,可以去看是否二叉搜索树,在这篇文章中,我具体分析了中序遍历得到序列。
Code:
int KthLargest ( BinTree T, int X )
{
int flag=0;
BinTree BT=T;
BinTree a[100]={NULL},b[100]={NULL};
int ai=0,bi=0,i;
while(BT||ai!=0)
{
while(BT)
{
a[ai++]=BT;
BT=BT->Left;
}
if(a[ai-1]==NULL)
ai--;
int top=--ai;
b[bi++]=a[top];
BT=a[top];
a[top]=NULL;
BT=BT->Right;
}
for(i=0;b[i]!=NULL;i++)
{
if(b[i]->Key==X)
{
flag=1;
break;
}
}
if(flag==0) return 0;
else return bi-i;
}