Given a Binary Search Tree (BST) and a positive integer k, find the k’th smallest element in the Binary Search Tree.
For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14.
We have discussed two methods in this post and one method in this post. All of the previous methods require extra space. How to find the k’th largest element without extra space?
We strongly recommend to minimize your browser and try this yourself first.Implementation
The idea is to use Morris Traversal. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. See this for more details.
Below is C++ implementation of the idea.
C++ Programming
#include<iostream>
#include<climits>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
int KSmallestUsingMorris(Node *root, int k)
{
int count = 0;
int ksmall = INT_MIN;
Node *curr = root;
while (curr != NULL)
{
if (curr->left == NULL)
{
count++;
if (count==k)
ksmall = curr->key;
curr = curr->right;
}
else
{
Node *pre = curr->left;
while (pre->right != NULL && pre->right != curr)
pre = pre->right;
if (pre->right==NULL)
{
pre->right = curr;
curr = curr->left;
}
else
{
pre->right = NULL;
count++;
if (count==k)
ksmall = curr->key;
curr = curr->right;
}
}
}
return ksmall;
}
Node *newNode(int item)
{
Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
Node* insert(Node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int main()
{
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
for (int k=1; k<=7; k++)
cout << KSmallestUsingMorris(root, k) << " ";
return 0;
}
[ad type=”banner”]
Output:
20 30 40 50 60 70 80