GATE | Sudo GATE 2020 Mock III (24 January 2019) | Question 30

Consider the same code as given in below question. The function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments.

filter_none

edit
close

play_arrow

link
brightness_4
code

// A BST node
struct node {
    int data;
    struct node *left, *right;
};
  
int count = 0;
  
void print(struct node *root, int k)
{
    if (X)
    {
        print(Y);
        count++;
        if (count == k)
          printf("%d ", root->data);
       print(root->left, k);
    }
}

chevron_right


If function print() prints the kth largest element in BST, then what should be X and Y?
(A) X = root != NULL && count >= k and Y = root->right, k
(B) X = root != NULL && count <= k and Y = root->right
(C) X = root != NULL && count >= k and Y = root->right
(D) X = root != NULL && count <= k and Y = root->right, k


Answer: (D)

Explanation: To prints the kth largest element in BST-:

filter_none

edit
close

play_arrow

link
brightness_4
code

// A BST node
struct node {
    int data;
    struct node *left, *right;
};
  
int count = 0;
  
void print(struct node *root, int k)
{
    if (root != NULL && count <= k)
    {
        print(root->right, k);
        count++;
        if (count == k)
          printf("%d ", root->data);
       print(root->left, k);
    }
}

chevron_right


So, X = root != NULL && count <= k and Y = root->right, k are correct.

Option (D) is true.

Quiz of this Question




My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.