二叉搜索树的第k个结点

题目:

给定一颗二叉搜索树,请找出其中的第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)这个递归函数中,怎么用二重指针,和引用来在递归中传递和返回参数的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值