230. Kth Smallest Element in a BST

本文介绍三种方法寻找二叉搜索树中第K小的元素:迭代中序遍历、递归中序遍历及使用二分查找优化的方法。针对频繁修改的情况提出了维护节点计数的优化方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

s思路:
1. bst. kth最小的话,那就是in-order遍历当计数器等于k就找到了,复杂度是o(n)
2. 如果经常修改,那么可以给每个把每个节点左右子树的节点个数作为一个member放在每个节点的private里面,就省事了,直接查询!用binary search即可
3.

//方法1:in-order, iterative,套路做法
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        //
        stack<TreeNode*> ss;
        TreeNode* cur=root;
        while(cur||!ss.empty()){
            while(cur){
                ss.push(cur);
                cur=cur->left;  
            }    
            cur=ss.top();
            ss.pop();
            if(--k==0) return cur->val;
            cur=cur->right; 
        }    
        return 0;
    }
};


//方法2:in-order, recursive,不套路,值得学习
//刚想的时候,还不晓得如何操作k,由于是in-order,所以就在操作根的时候--k即可!
class Solution {
public:
    void helper(TreeNode* root,int&k,int&res){
        if(!root) return;

        helper(root->left,k,res);//先左
        if(--k==0){//再根
            res=root->val;
            return;
        }
        helper(root->right,k,res);//后右
    }

    int kthSmallest(TreeNode* root, int k) {
        //
        int res=0;
        helper(root,k,res);
        return res;
    }
};

//方法3:binary search:但复杂度为o(nlgn)
class Solution {
public:

    int count(TreeNode* root){
        if(!root) return 0;
        return 1+count(root->left)+count(root->right);  
    }

    int kthSmallest(TreeNode* root, int k) {
        //
        int left=count(root->left);
        if(left+1>k){
            return kthSmallest(root->left,k);   
        }else if(left+1<k){
            return kthSmallest(root->right,k-left-1);
        }
        return root->val;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值