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 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 def inorder(node):
10 if not node:
11 return []
12 return inorder(node.left) + [node.val] + inorder(node.right)
13
14 return inorder(root)[k - 1]
This Python solution employs recursion to perform an in-order traversal, collecting node values in a list. The kth element is directly accessed by list indexing. This approach, however, uses O(n) space for storing the list.
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).
1#include <iostream>
2
3struct TreeNode {
4 int val;
5 TreeNode *left;
6 TreeNode *right;
7 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
8};
9
10int kthSmallest(TreeNode* root, int k) {
11 TreeNode* curr = root;
12 TreeNode* pre = nullptr;
13 int count = 0;
14 int result = 0;
15
16 while (curr) {
17 if (!curr->left) {
18 if (++count == k) result = curr->val;
19 curr = curr->right;
20 } else {
21 pre = curr->left;
22 while (pre->right && pre->right != curr) pre = pre->right;
23
24 if (!pre->right) {
25 pre->right = curr;
26 curr = curr->left;
27 } else {
28 pre->right = nullptr;
29 if (++count == k) result = curr->val;
30 curr = curr->right;
31 }
32 }
33 }
34
35 return result;
36}
In this C++ code, we use Morris In-Order Traversal to accomplish the task in O(1) space. By establishing back-links from nodes to their in-order successor temporarily, we can traverse the tree without using the function call stack.