题目:
给定一颗二叉搜索树,请找出其中的第k大的结点。
二叉搜索树的中序遍历是数值递增排序的,因此只需要中序遍历二叉搜索树,就可找到第k大的结点。
struct BinaryTree
{
int data;
BinaryTree *left;
BinaryTree *right;
};
//二叉搜索树的第K个结点
BinaryTree *KthNode(BinaryTree *pRoot,unsigned int k)
{
if(pRoot==NULL||k==o)
return pRoot;
return KthNodeCore(pRoot,k)
}
BinaryTree * KthNodeCore(BinaryTree *pRoot,unsigned int &k)
{
BinaryTree *target=NULL;
if(pRoot->left!=NULL)
target=KthNodeCore(pRoot->left,k);
if(target==NULL)
{
if(k==1)
target=pRoot;
k--;
}
if(target==NULL&&pRoot->right!=NULL)
target=KthNodeCore(pRoot->right,k);
return target;
}