PTA The Kth Largest X in BST(找X元素在BST二叉搜索树中是第几大元素)
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 */
For the following tree
解这道题的思路是从LeetCode上 230.Kth Smallest Element in a BST中得到的启发,LeetCode中的做法是进行中序遍历,得到一个递增序列,也就是左-中-右的遍历方式,于是我们可以将中序遍历换一个方向,也就是右-中-左的遍历方式,这样得到的就相当于是一个递减的序列,这个时候我们只需要将树进行遍历,当遇到X的时候输出在遍历到X之前所遍历到的节点个数再+1,就得到了Kth
代码如下
int n = 0;
int KthLargest(BinTree T, int X) {
return InorderTraversal(T, X);
}
int InorderTraversal(BinTree BT, int X) {
if (BT) {
InorderTraversal(BT->Right, X);
if (BT->Key == X) {
return n + 1;
}
else {
n++;
}
InorderTraversal(BT->Left, X);
}
// return 0;
}