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

示例 1:

输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 4

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
输出: 4

限制:

1 ≤ k ≤ 二叉搜索树元素个数

1.利用二叉搜索树右子树大于根节点,左子树小于根节点,所以中序遍历的结果递增有序的特性

①递归式写法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
vector<int> v;
    int kthLargest(TreeNode* root, int k) {//注意给的是二叉排序树
        if(root->left != NULL)
            kthLargest(root->left, k);
        v.push_back(root->val);
        if(root->right != NULL)
            kthLargest(root->right, k);
        if(k <= v.size())
            return v[v.size() - k];
        return 0;
    }
};

速度慢,内存大

②方法调用,

2.逆中序遍历,结果递减有序

用cnt遍历次数,提前返回,并不保存序列

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
int cnt, res;
    int kthLargest(TreeNode* root, int k) {
        cnt = k;
        ergodic(root);
        return res;
    }
    void ergodic(TreeNode* root){//逆中序,结果递减有序
        if(root->right != NULL)
            ergodic(root->right);
        cnt--;//代替中序的赋值
        if(cnt == 0) res = root->val;
        if(root->left != NULL)
            ergodic(root->left);
    }
};

速度内存有一点优化

上一篇:FastAPI(54)- 详解 Request 请求对象


下一篇:1042 Shuffling Machine (20 分)