问题描述:查找二叉查找树第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);
}
这篇博客介绍如何在二叉查找树中寻找第N个最大值。通过递归遍历树的右子节点,减少计数N,直到找到第N大的元素。提供了插入节点、打印树和寻找第N大元素的C语言实现代码。
771

被折叠的 条评论
为什么被折叠?



