PTA The Kth Largest X in BST(找X元素在BST二叉搜索树中是第几大元素)

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值