62、二叉搜索树的第k个结点

(个人水平有限,请见谅!)

题目描述:

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

代码示例:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
// 已经说明是二叉搜索树,前序遍历即可
class Solution {
    int index = 0;
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if (!pRoot) return NULL;
        TreeNode* ret = KthNode(pRoot->left, k);
        if (ret) return ret;
        if (++index == k) return pRoot;
        ret = KthNode(pRoot->right, k);
        if (ret) return ret;
        return NULL;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_30534935/article/details/87920085