剑指offer---二叉搜索树的第k个结点

题目:二叉搜索树的第k个结点

要求:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第3小的结点的值为4。

/*
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, int k)
    {
        
    }

    
};

解题代码:

class Solution {
public:
    int count = 0;
    TreeNode* KthNode(TreeNode* pRoot, int k){
        //中序遍历
        if(pRoot != nullptr){
            TreeNode* node = KthNode(pRoot->left, k);
            if(node != nullptr)
                return node;
            count++;
            if(count == k)
                return pRoot;
            node = KthNode(pRoot->right, k);
            if(node != nullptr)
                return node;
        }
        return nullptr;
    }
};
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9958748.html