Open In App

Data Structures | Binary Search Trees | Question 12

Like Article
Like
Save
Share
Report

Consider the same code as given in above question. What does the function print() do in general?

The function print() receives root of a Binary Search Tree (BST) and a positive integer k as arguments.




// 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);
    }
}


(A) Prints the kth smallest element in BST
(B) Prints the kth largest element in BST
(C) Prints the leftmost node at level k from root
(D) Prints the rightmost node at level k from root


Answer: (B)

Explanation: The function basically does reverse inorder traversal of the given Binary Search Tree. The reverse inorder traversal produces data in reverse sorted order. Whenever a node is visited, count is incremented by 1 and data of a node is printed only when count becomes k.

Quiz of this Question


Last Updated : 19 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads