剑指 Offer -- 二叉搜索树的第 K 个节点(六十二)

二叉搜索树的第 K 个节点(六十二)

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

代码(牛客上已 AC)

二叉搜索树的中序遍历是有序的数组, 因此可以使用一个计数器 idx 来判断当前访问的节点是不是第 K 个节点.

class Solution {
public:
    TreeNode* KthNode(TreeNode* root, int k) {
        int idx = 0;
        TreeNode *res = nullptr;
        KthNode(root, res, k, idx);
        return res;
    }
private:
    void KthNode(TreeNode *root, TreeNode* &res, int k, int &idx) {
        if (!root || k <= 0) return;
        KthNode(root->left, res, k, idx);
        idx ++;
        if (idx == k) {
            res = root;
            return;
        }
        KthNode(root->right, res, k, idx);
    }
};

你可能感兴趣的:(剑指,Offer,系列)