LeetCode Kth Smallest Element in a BST

本文介绍了一种高效的方法来找到二叉搜索树中第K小的元素,利用了二叉搜索树中序遍历的性质。通过递归或迭代的方式遍历树,并使用计数器记录已访问的节点数量,当计数器等于K时返回所需元素。此外,文章还探讨了在频繁修改的二叉搜索树中查找第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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).
思路分析:基本就是实现BST的中序遍历,BST中序遍历得到有序的数组,可以容易知道第k小数,以下给出了递归实现,借助counter记录当前遍历过的node数目,当counter==k时就可以返回。当然也可以借助栈实现迭代的解法。
Follow up: 进一步优化,我们可以在节点中额外保留一些信息: 左子树的大小. 在插入删除时也同时维护左子树的大小.进行查找时可以比较左子树size和k的大小,就可以知道要找的node在左边还是右边,通过分治法的思路加速. 时间复杂度为O(h)。
以下的伪代码摘录自 http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/
如果BST节点TreeNode的属性可以扩展,则再添加一个属性leftCnt,记录左子树的节点个数
记当前节点为node
当node不为空时循环:
若k == node.leftCnt + 1:则返回node
否则,若k > node.leftCnt:则令k -= node.leftCnt + 1,令node = node.right
否则,node = node.left
上述算法时间复杂度为O(BST的高度)

AC Code
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int res = 0;
    public int counter = 0;
    
    public int kthSmallest(TreeNode root, int k) {
        inOrderK(root, k);
        return res;
    }
    
    public void inOrderK(TreeNode root, int k){
        if(root.left!=null) inOrderK(root.left, k);
        counter++;
        
        if(counter == k) {
            res = root.val;
            return;
        }
        if(root.right!=null) inOrderK(root.right, k);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值