题目:
给定一颗二叉搜索树,请找出其中的第k大的结点(从小到大的第K个)
分析:
因为中序遍历二叉搜索树输出二叉树的结果是从小到大,所以我们实现中序遍历,这样打印出来的是从大到小的排序,从而当遍历到第k个节点的时候,停止遍历,并输出,用递归实现,把遍历的点的个数的引用传入函数中
PS:如果题目要求是从大到小实现,那么我们可以采取先遍历右节点再遍历左节点的思想
Code:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
{
TreeNode *tr = NULL;
unsigned int count = 0;
KthNodeCore(pRoot,&tr,count,k);
return tr;
}
void KthNodeCore(TreeNode* pRoot,TreeNode **tr,unsigned int &count,unsigned int k){
if(!pRoot)
return;
KthNodeCore(pRoot->left,tr,count,k);
count++;
if(k == count){
*tr = pRoot;
return;
}
KthNodeCore(pRoot->right,tr,count,k);
}
};
学习笔记:
主要学习:
void KthNodeCore(TreeNode* pRoot,TreeNode **tr,unsigned int &count,unsigned int k)
这个递归函数中,怎么用二重指针,和引用来在递归中传递和返回参数的