(二叉搜索树6-9)The Kth Smallest in BST--C语言

本文介绍了如何在给定的二叉搜索树中找到第K小的节点,通过中序遍历获取递增序列,然后直接返回第K-1个节点。给出了C语言代码示例和分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary search tree, you are supposed to find the node that contains the K-th smallest key.

Format of function:

BinTree KthSmallest ( 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 KthSmallest is supposed to return the pointer that points to the node that contains the K-th smallest key in the binary search tree T.

Here T is not empty and all its keys are distinct 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 */
BinTree KthSmallest ( BinTree T, int K );

int main()
{
    BinTree T, P;
    int K;

    T = BuildTree();
    scanf("%d", &K);
    P = KthSmallest(T, K);
    printf("%d\n", P->Key);
    if (P->Left) printf("%d\n", P->Left->Key);
    else printf("NULL\n");
    if (P->Right) printf("%d\n", P->Right->Key);
    else printf("NULL\n");

    return 0;
}
/* Your function will be put here */

Sample Input: (for the following tree)

在这里插入图片描述

5

Sample Output:

5
NULL
7

Analysis:

用中序遍历得到序列,因为是二叉搜索树,则该序列一定是递增的,所以直接返回序列中第k个数(下标为k-1)。

Notice:

  • 如果不知道怎么用中序遍历得到序列,可以去看是否二叉搜索树,在这篇文章中,我具体分析了中序遍历得到序列。
  • 序列中储存的是地址,因此直接返回即可。

Code:

BinTree KthSmallest ( BinTree T, int K )
{
    BinTree BT=T; 
    BinTree a[100]={NULL},b[100]={NULL};
    int ai=0,bi=0;
    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;
    }
    return b[K-1];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值