天天看點

劍指 Offer -- 二叉搜尋樹的第 K 個節點(六十二)

二叉搜尋樹的第 K 個節點(六十二)

代碼(牛客上已 AC)

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);
    }
};