Skip to content

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

@MyLinChi

Description

@MyLinChi

问题

给定一棵二叉搜索树,请找出其中第k大的节点。

求解

搜索二叉树的中序遍历是有序的。

class Solution {
private:
    bool flag;
    int k;
    int res;
    void treeCount(TreeNode* root) {
        if (root == nullptr)return;
        treeCount(root->right);
        if(--k==0)res = root->val;
        treeCount(root->left);
    }
public:
    int kthLargest(TreeNode* root, int k) {
        flag = false;
        this->k = k;
        treeCount(root);
        return res;
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions