In a Binary Search Tree (BST), an in-order traversal visits nodes in ascending order. To find the kth smallest element, perform an in-order traversal and count the nodes until you reach the kth one.
Time Complexity: O(n), Space Complexity: O(n) (due to recursion stack in worst case).
1class Solution {
2 static class TreeNode {
3 int val;
4 TreeNode left, right;
5 TreeNode(int x) { val = x; }
6 }
7
8 public int kthSmallest(TreeNode root, int k) {
9 int[] result = new int[2];
10 inorder(root, result, k);
11 return result[1];
12 }
13
14 private void inorder(TreeNode node, int[] result, int k) {
15 if (node == null) return;
16 inorder(node.left, result, k);
17 if (++result[0] == k) {
18 result[1] = node.val;
19 return;
20 }
21 inorder(node.right, result, k);
22 }
23}
In this Java solution, an integer array is used to hold the count and the result concurrently. The traversal is stopped once the kth smallest element is found by updating the result array.
Morris Traversal is a way to perform in-order traversal with O(1) extra space. This method modifies the tree's structure temporarily to avoid the recursive call stack. This approach uses the concept of threading where leaf nodes point to their in-order successor to facilitate traversal.
Time Complexity: O(n), Space Complexity: O(1).
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def kthSmallest(self, root: TreeNode, k: int) -> int:
9 current = root
10 count = 0
11 result = 0
12
13 while current:
14 if not current.left:
15 count += 1
16 if count == k:
17 return current.val
18 current = current.right
19 else:
20 predecessor = current.left
21 while predecessor.right and predecessor.right is not current:
22 predecessor = predecessor.right
23
24 if not predecessor.right:
25 predecessor.right = current
26 current = current.left
27 else:
28 predecessor.right = None
29 count += 1
30 if count == k:
31 return current.val
32 current = current.right
The Python code implements Morris In-Order Traversal, leading to O(1) auxiliary space usage. The traversal efficiently visits nodes while keeping changes to the tree structure temporary.