Wednesday, February 25, 2009

Kth Element in the Binary Search Tree

Given a Binary Search Tree, write a program to print the kth smallest element without using any static/global variable. You cant pass the value k to any function also.

Solution: In case you are allowed to use the extra space, and there is no condition you just have to specify the kth element in the binary search tree. You can simply do inorder and keep a counter, when the counter becomes equal to k print the element

The code for that would be:

KthElement(struct node * root, int count, int k)
{
if( root)
{
KthElement(root->left, count,k);
count ++;
if( count == k)
return root->data;
KthElement(root->right,count,k);
}
}

to follow the condition of the above question, we dont have to pass the value of the variable to it and we cant keep any global variable. We can do it by doing the inorder in an iterative manner. Logic would be.
Use a stack. Traverse till the left and while traversing push the nodes in the stack.
Pop each node from the stack and then traverse to its right and again iteratively follow the same procedure of going to left and so on.

The code would look like this:

KthElementIterative(struct node * root, int k)
{
struct node * temp = root;
struct node * x;

push(root);
temp = temp->left;

while( stack is not empty)
{

while( temp ! = NULL)
{
push( temp );
temp = temp ->left;
}

x = pop();
count ++;

if(count == k )
break;


if( x->right)
{push(x-right);temp = x->right;}

else temp=null;

}

return x->data;
}

1 comment: