问题描述:查找二叉查找树第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);
}