[Naive Approach] Using Inorder Traversal - O(n) Time and O(n) Space
The idea is to traverse BST in inorder traversal. Note that Inorder traversal of BST accesses elements in sorted (or increasing) order. While traversing, we keep track of count of visited Nodes and keep adding Nodes until the count becomes k.
Below is the implementation of the above approach:
Output
17
Time complexity: O(n), where n is the number of nodes in the Binary Search Tree, as the algorithm performs an inorder traversal visiting each node once. Auxiliary Space: O(h),where h is the height of the tree, due to the recursive call stack. In the worst case (skewed tree), it can be O(n).
[Expected Approach] Using Morris Traversal - O(n) Time and O(1) Space
The idea is to use Morris Traversal , this method establishes temporary threads (links) to allow traversal and reverts these changes afterward to restore the original tree structure. By counting nodes during traversal, we can compute the cumulative sum of the k nodes visited.
Follow the steps below to solve the problem:
Initialize current as root, and counter, result to store the count and sum of elements found.
If current has no left child:
Increment counter and add current's data to answer.
If counter == k, return answer.
Move to the right by updating current as current'right.
Otherwise:
Find the rightmost node in current's left subtree (inorder predecessor) or a node whose right child is current.
If the right child of the found node is current, restore the original tree:
Set the right child of the node to NULL, increment counter, add current's data to answer, and
if counter == k, return answer.
Move to the right by updating current as current'right.
Otherwise, set current as the right child of the rightmost node.
Below is implementation of above approach :
Output
17
Time Complexity: O(k), since we only traverse the tree until the k-th smallest element. Auxiliary Space:O(1), for the iterative approach, as it uses a constant amount of space, with no additional data structures aside from a few variables.