查找二叉查找树第N大的数

这篇博客介绍如何在二叉查找树中寻找第N个最大值。通过递归遍历树的右子节点,减少计数N,直到找到第N大的元素。提供了插入节点、打印树和寻找第N大元素的C语言实现代码。

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

问题描述:查找二叉查找树第N大的数

代码:

#include<stdio.h>

#include<stdlib.h>

typedefstruct BSTreeNode

{

int Value;

struct BSTreeNode *pLeft;

struct BSTreeNode *pRight;

}*pBSTreeNode,BSTreeNode;

void FindNthMax(pBSTreeNode root,int &N,int &Result)

{

if(root!=NULL)

{

FindNthMax(root->pRight,N,Result);

if(--N==0)

{

Result = root->Value;

}

FindNthMax(root->pLeft,N,Result);

}

}

void Insert(pBSTreeNode &root,int value)

{

if(root==NULL)

{

root=(pBSTreeNode)malloc(sizeof(BSTreeNode));

root->Value=value;

root->pLeft=NULL;

root->pRight=NULL;

}

else

{

if(value<root->Value)

Insert(root->pLeft,value);

elseif(value>root->Value)

Insert(root->pRight,value);

else

printf("duplicated value\n");

}

}

void Print(pBSTreeNode root)

{

if(root!=NULL)

{

Print(root->pLeft);

printf("Value:%d\n",root->Value);

Print(root->pRight);

}

}

void main()

{

pBSTreeNode root=NULL;

int value,j;

printf("Enter the Number of Tree:");

scanf("%d",&j);

for(int i=0;i<j;i++)

{

printf("Enter value:");

scanf("%d",&value);

Insert(root,value);

}

Print(root);

int N=4;

int result;

FindNthMax(root,N,result);

printf("The 4 th Max Node Value:%d\n",result);

}

                                                        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值