【两次过】Lintcode 902. BST中第K小的元素

本文介绍了一种在二叉搜索树中查找第K小元素的方法,提供了递归和非递归两种中序遍历的解决方案。通过具体样例展示了如何实现这一功能,并讨论了当树经常被修改时如何优化查找过程。

给一棵二叉搜索树,写一个 KthSmallest 函数来找到其中第 K 小的元素。

样例

样例 1:

输入:{1,#,2},2
输出:2
解释:
	1
	 \
	  2
第二小的元素是2。

样例 2:

输入:{2,1,3},1
输出:1
解释:
  2
 / \
1   3
第一小的元素是1。

挑战

如果这棵 BST 经常会被修改(插入/删除操作)并且你需要很快速的找到第 K 小的元素呢?你会如何优化这个 KthSmallest 函数?

注意事项

你可以假设 k 总是有效的, 1 ≤ k ≤ 树的总节点数


解题思路1:

中序遍历即可。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
     int res = 0;
     int kk = 0;
    public int kthSmallest(TreeNode root, int k) {
        // write your code here
        kk = k;
        
        kthSmallest(root);
        
        return res;
    }
    
    private void kthSmallest(TreeNode root){
        if(root == null)
            return;
            
        kthSmallest(root.left);
        
        if(--kk == 0)
            res = root.val;
        
        kthSmallest(root.right);
    }
}

解题思路2:

中序遍历的非递归版本。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
    public int kthSmallest(TreeNode root, int k) {
        // write your code here
        Stack<TreeNode> stack = new Stack<>();
        
        while(root!=null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();
            
            if(--k == 0)
                return root.val;
            
            root = root.right;
        }
        
        return 0;
    }

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值