标签:
题目:给定一棵二叉搜索树,请找出其中的第K大的结点。例如在下图中的二叉树,第四个结点就是:5.
#include <iostream>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree *pLeft;
BinaryTree *pRight;
};
BinaryTree *pRoot=NULL;
int arr[7]={5,3,7,2,4,6,8,};
void InsertTree(BinaryTree *tree,int data)
{
if(tree->data > data) //插入在左边;
{
if(tree->pLeft==NULL)
{
BinaryTree *node=new BinaryTree;
node->data=data;
node->pLeft=node->pRight=NULL;
tree->pLeft=node;
}
else
InsertTree(tree->pLeft,data);
}
else//插入在右边;
{
if(tree->pRight==NULL)
{
BinaryTree *node=new BinaryTree;
node->data=data;
node->pLeft=node->pRight=NULL;
tree->pRight=node;
}
else
InsertTree(tree->pRight,data);
}
}
void CreateTree(BinaryTree * &root,int length,int *array)
{
for(int i=0;i<length;i++)
{
if(root==NULL)
{
root=new BinaryTree;
root->data=array[i];
root->pLeft=root->pRight=NULL;
}
else
InsertTree(root,array[i]);
}
}
BinaryTree *GetKthNode(BinaryTree *root,int &k)
{
BinaryTree *target=NULL;
if(root->pLeft!=NULL)
target=GetKthNode(root->pLeft,k);
if(target==NULL)
{
if(k==1)
target=root;
k--;
}
if(target==NULL && root->pRight!=NULL)
target=GetKthNode(root->pRight,k);
return target;
}
BinaryTree *KthNode(BinaryTree *root,int k)
{
if(NULL==root || k<=0)
return NULL;
return GetKthNode(root,k);
}
int main()
{
BinaryTree *result=NULL;
CreateTree(pRoot,7,arr);
result=KthNode(pRoot,4);
if(result)
cout<<"第四个结点是:"<<result->data<<endl;
else
cout<<"输入有误!"<<endl;
system("pause");
return 0;
}
运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51788074