剑指offer 54:二叉搜索树的第k大节点

在这里插入图片描述
思路
二叉搜索树的中序遍历就是将所有节点从小到大排列,那么如果是从大到小排列,第k个节点就是第k大的节点了。因此在中序遍历的过程中只要先遍历右子树,后遍历左子树即可。

class Solution {
    
    
private:
    int count = 0, res = 0;
public:
    void inorder(TreeNode* root, int k) {
    
    
        if (root == nullptr) return;
        inorder(root->right, k);
        ++count;
        if(count == k) {
    
    
            res = root->val;
            return;
        }
        inorder(root->left, k);
    }
    int kthLargest(TreeNode* root, int k) {
    
    
        inorder(root, k);
        return res;
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114108643