The Kth Largest X in BST--C语言

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=-1;
    BinTree BT; 
    BinTree a[100]={NULL};
    BinTree b[100]={NULL};
    int ai,bi;
    ai=bi=0;
    BT=T;
    while(BT||ai!=0)
    {
        while(BT)
        {
            a[ai]=BT;
            ai++;
            BT=BT->Left;
        }
        if(a[ai-1]==NULL)
        {
            ai--;
        }
        b[bi]=a[ai-1];
        BT=a[ai-1];
        a[ai-1]=NULL;
        bi++;
        ai--;
        BT=BT->Right;
    }
    int count=0;
    for(int i=0;b[i]!=NULL;i++)//统计树中总共有多少数
        count++;
    int i;
    for(i=0;b[i]!=NULL;i++)
    {
        if(b[i]->Key==X)
        {
            flag=1;
            break;
        }
    }
    if(flag==-1)
        flag=0;
    if(flag==0)//树中没找到X
        return 0;
    else
        return count-i;
}
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值