Leetcode 230. Kth Smallest Element in a BST
Given the root of a binary search tree (BST) and an integer k
, return the k
-th smallest element in the tree.
Example:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Q: Can the values in the BST be negative and positive? A: Yes, values can be any integer.
Q: Can we assume that k
is always valid, i.e., 1 <= k <= number of nodes in the BST
?
A: Yes, you can assume that k
is always valid.
Q: What is the maximum number of nodes in the BST?
A: The number of nodes is 10^4
as per typical constraints.
Q: Should the solution be optimized for space or time complexity? A: A balanced approach is preferred, though typically time complexity is emphasized.
To find the k
-th smallest element in a BST, we can leverage the properties of the tree:
We will keep track of the number of elements processed and return the k
-th element during the traversal.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
private int count = 0;
private int result = -1;
public int kthSmallest(TreeNode root, int k) {
inOrderTraversal(root, k);
return result;
}
private void inOrderTraversal(TreeNode node, int k) {
if (node == null) {
return;
}
inOrderTraversal(node.left, k);
count++;
if (count == k) {
result = node.val;
return;
}
inOrderTraversal(node.right, k);
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?