GATE Computer ScienceVery hardGATE CS (PYQ pattern)

bool f(Node *n) { if (!n) return true; if (n->l && n->l->k > n->k) return false; if (n->r && n->r->k < n->k) return false; return f(n->l) && f(n->r); } The tree as (key, left, right): P = (20, (10, (5), (25)), (30)); Q = (20, (10, -, (15)), (30, (25), (40))); R = (20, (10), (30, (15), -)); S = (20, (10, (5), (12)), (30, (25), (35))). For which of these does f return true although the tree is not a BST?

  1. A. P and R only
  2. B. P, Q and R only
  3. C. R and S only
  4. D. P only

Correct answer: A. P and R only

f only compares each node with its direct children. P (25 under 10 is in 20's left subtree), R (15 under 30 is in 20's right subtree) pass f but break the BST property; Q and S are genuine BSTs.

More Programming and Data Structures (GATE) questions

Exams that ask this topic