二叉搜索树的第k个节点(C++)

题目:

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

思路:

因为时二叉搜索树(满足left

代码实现:

/*
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)
    {
        if(pRoot == nullptr || k <= 0)
            return nullptr;
        return KthNodeCore(pRoot, k);
    }
    /*---采用中序遍历,则中序遍历数组中的第k个结果即为需要的结果---*/
    TreeNode* KthNodeCore(TreeNode* pRoot, int &k)
    {
        TreeNode* result = nullptr;
        if(pRoot->left != nullptr)
            result = KthNodeCore(pRoot->left, k);
        if(result == nullptr)
        {
            if(k == 1)
                result = pRoot;
            k--;
        }
        if(result == nullptr && pRoot->right != nullptr)
            result = KthNodeCore(pRoot->right, k);
        return result;
    }
};

 

你可能感兴趣的:(C++)