Given root of binary search tree and K as input, find K-th smallest element in BST.
For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14.
Method 1: Using Inorder Traversal.
Inorder traversal of BST retrieves elements of tree in the sorted order. The inorder traversal uses stack to store to be explored nodes of tree (threaded tree avoids stack and recursion for traversal, see this post). The idea is to keep track of popped elements which participate in the order statics. Hypothetical algorithm is provided below,
Time complexity: O(n) where n is total nodes in tree..
/* initialization */ pCrawl = root set initial stack element as NULL (sentinal) /* traverse upto left extreme */ while(pCrawl is valid ) stack.push(pCrawl) pCrawl = pCrawl.left /* process other nodes */ while( pCrawl = stack.pop() is valid ) stop if sufficient number of elements are popped. if( pCrawl.right is valid ) pCrawl = pCrawl.right while( pCrawl is valid ) stack.push(pCrawl) pCrawl = pCrawl.left
Method 2: Augmented Tree Data Structure.
The idea is to maintain rank of each node. We can keep track of elements in a subtree of any node while building the tree. Since we need K-th smallest element, we can maintain number of elements of left subtree in every node.
Assume that the root is having N nodes in its left subtree. If K = N + 1, root is K-th node. If K < N, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > N + 1, we continue our search in the right subtree for the (K – N – 1)-th smallest element. Note that we need the count of elements in left subtree only.
Time complexity: O(h) where h is height of tree.
start: if K = root.leftElement + 1 root node is the K th node. goto stop else if K > root.leftElements K = K - (root.leftElements + 1) root = root.right goto start else root = root.left goto start stop:
Thanks to Venki for providing post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find median of BST in O(n) time and O(1) space
- K'th smallest element in BST using O(1) Extra Space
- K'th Largest Element in BST when modification to BST is not allowed
- Binary Search Tree | Set 1 (Search and Insertion)
- Find a pair with given sum in a Balanced BST
- Floor and Ceil from a BST
- Two nodes of a BST are swapped, correct the BST
- Check if each internal node of a BST has exactly one child
- Merge two BSTs with limited extra space
- Find the largest BST subtree in a given Binary Tree | Set 1
- Sorted Array to Balanced BST
- Print BST keys in the given range
- Inorder Successor in Binary Search Tree
- A program to check if a binary tree is BST or not
- Find the node with minimum value in a Binary Search Tree
Improved By : Dheerain Jain