给一棵二叉搜索树,写一个 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;
}
}

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

被折叠的 条评论
为什么被折叠?



