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:
great work.
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.
you are setting the value of index to 0 in every recursion!
it's a static variable.
that static int is smart. I had a similar implementation, but instead I used a public variable. Really smart.
Post a Comment