Web Toolbar by Wibiya

Pages

Monday, January 16, 2012

Find the kth largest element in a Binary Search Tree.

Solution #1: Traverse the tree in descending order and keep a count of number of nodes visited. When this count is equal to 'k', print the element. Here is the  code,

void printk(struct node* root, int k)
{
    if(root == NULL)
        return;

    static int index = 0;

    printk(root->right, k);

    if(++index == k)
    {
        printf("%d\n", root->data);
        return;
    }

    printk(root->left, k);
}

5 comments:

Unknown said...

great work.

Unknown said...

Can you please suggest a solution for:
In a BST, given a node val, find the 2nd largest element with respect to the given node val.

Anonymous said...

you are setting the value of index to 0 in every recursion!

Anonymous said...

it's a static variable.

Anonymous said...

that static int is smart. I had a similar implementation, but instead I used a public variable. Really smart.