Kth Smallest Element in a BST : **
这个题目,俩种方法都不错。都是练习了我的盲点。
//Method 1 Binary Search
//helper用到了返回一棵树的node 数的小方法
//主题核心思想是binary search,非常类似于用quick sort 找kth element in unsorted array 那个题目。 个人很喜欢这俩道题。
public class Solution {
public int kthSmallest(TreeNode root, int k) {
int n = helper(root.left);
if( n == k-1){
return root.val;
}else if( n >= k){
return kthSmallest(root.left,k);
}else{
return kthSmallest(root.right,k-n-1);
}
}
public int helper(TreeNode node){
if(node == null){
return 0;
}
return helper(node.left) + helper(node.right) + 1;
}
}
//Method 2 Iterate over a BT in-order using stack
//这个方法第一学期算法课上写过sudo code。。。时隔大半年了,第一次实现。。
//有个tricky的地方,一开始先加一个 root进去,注意这里root加了俩遍。这样在root 所有left边node处理完之后,stack不会empty,
//才能继续处理右边,要不然直接结束循环就不对了。这只是一种方法,回头遇到更好的实现再来update
public int kthSmallest(TreeNode root, int k) {
LinkedList
stack = new LinkedList
();
TreeNode node = root;
stack.push(root);
int count = 0;
while(!stack.isEmpty()){
while(node != null){
stack.push(node);
node = node.left;
}
TreeNode top = stack.pop();
count ++;
if(count == k){
return top.val;
}
node = top.right;
}
return 0;
}
本文介绍了两种解决二叉搜索树中寻找第K小元素问题的方法,采用二分搜索和中序遍历。通过辅助方法计算左子树节点数量,优化了查找过程。同时,通过迭代中序遍历使用栈结构实现,巧妙地解决了树的遍历问题,适合算法爱好者深入学习。
312

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



