230. Kth Smallest Element in a BST

本文探讨了在二叉搜索树中寻找第K小元素的有效算法,包括迭代和递归方法。通过利用二叉搜索树的性质,我们实现了时间复杂度为O(树的高度)的解决方案,优化了频繁查找场景下的效率。

230. Kth Smallest Element in a BST


题目:

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?

Hint:

Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
链接: http://leetcode.com/problems/kth-smallest-element-in-a-bst/

方法1:

用173题的思路,implement一个iterator。时间复杂度是O(h),空间复杂度是O(h),因为有可能需要遍历右孩子的左子树path?

code

方法2: iterative

边记录边入栈,不需要全部入栈,利用count来记录已获取node的数量。这样当提前取满的时候就可以退出,否则inorder traversal全部需要O(n)

code

犯过的错:

  1. inorder traversal 练的不熟
  2. 被quote掉的循环造成k在循环内清零
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int result;
        stack<TreeNode*> myStack;
        
        
        while(k > 0){
            if (root){
                myStack.push(root);
                root = root->left;
            }
            else{
                //while(!myStack.empty()){
                if (myStack.empty()) break;
                root = myStack.top();
                myStack.pop();
                result = root->val;
                k--;
                // if (root != nullptr){
                    root = root->right;
                //}
           // }
                
            }
            
            
        }
        return result;
    }
};

方法3: recursion

剪枝

code

public class Solution {
    List<Integer> nodeVal = new ArrayList<Integer>();
    
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return nodeVal.get(k - 1);
    }
    
    private void inorder(TreeNode root, int k) {
        if(nodeVal.size() >= k)
            return;
        if(root == null)
            return;
        inorder(root.left, k);
        nodeVal.add(root.val);
        inorder(root.right, k);
        
    }
}

或者

public class Solution {
    
    private int count = 0;
    private int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return res;
    }
    
    private void inorder(TreeNode root, int k) {
        if(root == null)
            return;
        if(count >= k)
            return;
        inorder(root.left, k); 
        if(count >= k)
            return;
        res = root.val;
        count++;
        inorder(root.right, k);
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值