剑指 Offer 54. 二叉搜索树的第k大节点

63 阅读1分钟

c++

class Solution {
public:
    int getCount(TreeNode *root) {
        if (root == NULL) return 0;
        return getCount(root->left) + getCount(root->right) + 1;
    }

    int kthLargest(TreeNode* root, int k) {
        int rn = getCount(root->right);
        if (k == rn + 1) return root->val;
        if (k <= rn) return kthLargest(root->right, k);
        return kthLargest(root->left, k - rn - 1); 
    }
};

js

var CountNode = function(root) {
    if (root === null) return 0;
    return CountNode(root.left) + CountNode(root.right) + 1;
}
var kthLargest = function(root, k) {
    var rn = CountNode(root.right);
    if (k == rn + 1) return root.val;
    if (k <= rn) return kthLargest(root.right, k);
    return kthLargest(root.left, k - rn - 1); 
};