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

标签: 剑指 Offer 发布于:2022-02-27 16:52:37 编辑于:2022-02-27 16:52:37 浏览量:802

概述

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

中序遍历

实现的时候注意,count 放全局变量好搞一些。

class Solution {
public:
    int i = 0;
    int k;
    int ans = -1;
    int count = 0;
    int kthLargest(TreeNode* root, int k) {
        this->k = k;
        helper(root);
        return ans;
    }

    void helper(TreeNode* root) {
        if (count >= k) return;
        if (!root) return;
        helper(root->right);
        count ++;
        if (count == k) {
            ans = root->val;
            return;
        }
        helper(root->left);
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/