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).
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var kthSmallest = function(root, k) {
8 let count = 0;
9 let result = null;
10
11 function inorder(node) {
12 if (!node) return;
13 inorder(node.left);
14 if (++count === k) {
15 result = node.val;
16 return;
17 }
18 inorder(node.right);
19 }
20
21 inorder(root);
22 return result;
23};
This JavaScript solution operates recursively. A counter keeps track of the number of visited nodes during an in-order traversal. Once the kth node is visited, the counter matches k, and the result is set to the current node's value.
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.