题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
思路:采用递归,每次计算左子树个数,则该节点为左子树个数加1个节点。判断其与k的大小比较,往左往右递归。
//二叉搜索树的第k个结点
#include <iostream>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
int countTreeNode(TreeNode* pRoot)
{
int count_left=0,count_right=0;
if(pRoot==NULL)
return 0;
if(pRoot->left==NULL&&pRoot->right==NULL)
return 1;
if(pRoot->left!=NULL)
count_left=countTreeNode(pRoot->left);
if(pRoot->right!=NULL)
count_right=countTreeNode(pRoot->right);
return 1+count_left+count_right;
}
TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
{
if(k<=0)
return NULL;
int count_left=0,count_right=0;
if(pRoot==NULL)
return 0;
if(pRoot->left!=NULL)
count_left=countTreeNode(pRoot->left);
if(count_left==k-1)
return pRoot;
else if(count_left>k-1)
return KthNode(pRoot->left,k);
else
{
if(pRoot->right!=NULL)
return KthNode(pRoot->right,k-count_left-1);
else
return NULL;
}
}
void main()
{
TreeNode no1(7),no2(4),no3(9),no4(2),no5(6),no6(8),no7(10),no8(1),no9(3),no10(5);
no1.left=&no2;
no1.right=&no3;
no2.left=&no4;
no2.right=&no5;
no3.left=&no6;
no3.right=&no7;
no4.left=&no8;
no4.right=&no9;
no5.left=&no10;
TreeNode* pnode=KthNode(&no1,15);
cout<<pnode->val;
system("pause");
}