Popular Posts

Monday, January 31, 2011

Find Kth largest and smallest number in BST

How to find kth smallest element in BST. you cannot use static/global variable and you cannot pass value of k to any function ?
Solution : Make in order traversal and out put the kth element.
Let each node in the BST have a field that returns the number of elements in its left and right subtree. Let the left subtree of node T contain only elements smaller than T and the right subtree only elements larger than or equal to T.
Now, suppose we are at node T:
1.       k == num_elements(left subtree of T), then the answer we're looking for is the value in node T
2.       k > num_elements(left subtree of T) then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
3.       k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.
This is O(log N) on average (assuming a balanced tree).

Java code:

public int ReturnKthSmallestElement1(int k)
{
Node node = Root;

int count = k;

int sizeOfLeftSubtree = 0;

while(node != null)
{

sizeOfLeftSubtree = node.SizeOfLeftSubtree();

if (sizeOfLeftSubtree + 1 == count)
return node.Value;
else if (sizeOfLeftSubtree < count)
{
node = node.Right;
count -= sizeOfLeftSubtree+1;
}
else
{
node = node.Left;
}
}

return -1;
}
find(node, k) {
  if (count(node->left) + 1 == k) result = node;
  else if (count(node->left) < k) result = find(node->right, k - count(node->left) - 1);
  return find(node->left, k);
For largest element use node->right
struct tree* findkthsmallest(struct tree* t,int k)
{
int left_size=0;

if(t->left!=NULL) left_size=t->left->size;

if(left_size+1==k) return t;

else if(k<=left_size) return findkthsmallest(t->left,k);

else return findkthsmallest(t->right,k-left_size-1);//find k-left_size-1 smallest in right subtree.
}

struct tree* findkthlargest(struct tree* t,int k)
{
int right_size=0;

if(t->right!=NULL) right_size=t->right->size;

if(right_size+1==k) return t;

else if(k<=right_size) return findkthlargest(t->right,k);

else return findkthlargest(t->left,k-right_size-1);
}

No comments:

Post a Comment