Statementâ–¼
Given the root node of a binary search tree and an integer value k
, return the kth smallest value in the tree.
Constraints:
- The number of nodes in the tree is n.
- 1≤k≤n≤500
- 0≤
Node.data
≤104
Solution
For this solution, we will recursively perform the inorder traversal(left subtree, root, right subtree) on the binary search tree. We will use the inorder traversal to get elements in sorted order.
While performing the inorder traversal on the tree, decrement k
by 1, indicating the number of smaller elements that still need to be found. After decrementing k
, we check whether the value of k
has reached 0. If it is 0, we return the current node, indicating the node having the kth smallest element. If not, continue the traversal.
This approach ensures that we traverse the tree in a depth-first manner while appropriately updating k
and effectively finding the kth smallest element.
Now, let’s look at the following illustration to get a better understanding of the solution: