Topic
- Binary Search
- Tree
Description
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
Given the root
of a binary search tree, and an integer k
, return the k
th (1-indexed) smallest element in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
The number of nodes in the tree is n
.
- $1 \leqslant k \leqslant 10^4$
- $0 \leqslant Node.val \leqslant 10^4$
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Analysis
方法一:我寫的遞歸法(BST的中序遍歷)
方法二:我寫的迭代法
方法三:別人寫的迭代法
Submission
import java.util.LinkedList;
import com.lun.util.BinaryTree.TreeNode;
public class KthSmallestElementInABST {
//方法一:我寫的遞歸法(BST的中序遍歷)
public int kthSmallest(TreeNode root, int k) {
int[] result = {-1}, count = {0};
inorder(root, k, result, count);
return result[0];
}
private void inorder(TreeNode root, int k, int[] result, int[] count) {
if(root == null || result[0] != -1) return;
inorder(root.left, k, result, count);
if(++count[0] == k) {
result[0] = root.val;
return;
}
inorder(root.right, k, result, count);
}
//方法二:我寫的迭代法
public int kthSmallest2(TreeNode root, int k) {
LinkedList<object[]> stack = new LinkedList<>();
stack.push(new Object[] {root, 0});//0, 1, 2, 3 = 左,中,右,pop
int count = 0;
while(!stack.isEmpty()) {
Object[] arr = stack.peek();
TreeNode node = (TreeNode)arr[0];
int state = (int)arr[1];
if(state == 0) {
if(node.left != null)
stack.push(new Object[] {node.left, 0});
arr[1] = 1;
}else if(state == 1) {
if(++count == k)
return node.val;
arr[1] = 2;
}else if(state == 2) {
if(node.right != null)
stack.push(new Object[] {node.right, 0});
arr[1] = 3;
}else {
stack.pop();
}
}
return -1;
}
//方法三:別人寫的迭代法
public int kthSmallest3(TreeNode root, int k) {
LinkedList<treenode> stack = new LinkedList<treenode>();
TreeNode p = root;
int count = 0;
while(!stack.isEmpty() || p != null) {
if(p != null) {
stack.push(p); // Just like recursion
p = p.left;
} else {
TreeNode node = stack.pop();
if(++count == k) return node.val;
p = node.right;
}
}
return -1;
}
}
Test
import static org.junit.Assert.*;
import org.junit.Test;
import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;
public class KthSmallestElementInABSTTest {
@Test
public void test() {
KthSmallestElementInABST obj = new KthSmallestElementInABST();
TreeNode root1 = BinaryTree.integers2BinaryTree(3, 1, 4, null, 2);
TreeNode root2 = BinaryTree.integers2BinaryTree(5, 3, 6, 2, 4, null, null, 1);
assertEquals(1, obj.kthSmallest(root1, 1));
assertEquals(3, obj.kthSmallest(root2, 3));
assertEquals(1, obj.kthSmallest2(root1, 1));
assertEquals(3, obj.kthSmallest2(root2, 3));
assertEquals(1, obj.kthSmallest3(root1, 1));
assertEquals(3, obj.kthSmallest3(root2, 3));
}
}
</treenode></treenode></object[]>