welcome to my blog
LeetCode Top Interview Questions 230. Kth Smallest Element in a BST (Java版; Medium)
题目描述
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.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
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?
class Solution {
private int order = 0;
public int kthSmallest(TreeNode root, int k) {
if(root==null){
return 0;
}
int L = kthSmallest(root.left, k);
if(order==k){
return L;
}
order++;
if(order==k){
return root.val;
}
return kthSmallest(root.right, k);
}
}
第一次做; 循环版中序遍历, 核心: 不单独处理root, 当cur!=null || stack不为空时执行循环, 循环中有两个分支, 当cur!=null时, cur压栈, cur=cur.left; 当cur==null时, cur指向弹出的栈顶元素并打印, cur=cur.right
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur!=null || !stack.isEmpty()){
if(cur!=null){
stack.push(cur);
cur = cur.left;
}
else{
cur = stack.pop();
k--;
if(k==0)
return cur.val;
cur = cur.right;
}
}
//不会执行到这里, 写这个return是为了编译通过
return -1;
}
}
第一次做; 核心:使用两个全局变量记录遍历过的节点的个数和第k个元素; 设置一个全局变量flag, 帮助递归函数进行剪枝操作, 也就是提前返回, 如果flag为true, 则说明找到第k个元素了, 不需要继续遍历二叉树了
class Solution {
public int i, res;
//标志位, true表示已经找到第k个元素, 作用:剪枝, 找到第k个元素后就不用继续遍历了
public boolean flag;
public int kthSmallest(TreeNode root, int k) {
core(root, k);
return res;
}
public void core(TreeNode root, int k){
//base case
if(flag==true)
return;
if(root==null)
return;
//
core(root.left, k);
i++;
if(i==k){
flag = true;
res = root.val;
}
core(root.right, k);
}
}
第一次做; 核心:使用两个全局变量记录遍历过的节点的个数和第k个元素; 该版本没有剪枝
/*
就是中序遍历的第k个元素
递归版和非递归版都来一遍吧
难点: 怎么返回第k个数? 使用全局变量
*/
//这么写递归函数不能剪枝, 也就是会遍历整棵二叉树, 要想剪枝的话需要单独写一个递归函数
class Solution {
//记录遍历过的节点的个数
public int i;
//记录第k个元素的值
public int res;
public int kthSmallest(TreeNode root, int k) {
if(root==null)
return 0;
//
kthSmallest(root.left,k);
//
i++;
if(i==k)
res = root.val;
//
kthSmallest(root.right,k);
//
return res;
}
}