GATE Computer ScienceHardGATE CS (PYQ pattern)

Keys 50, 30, 80, 20, 40, 70, 90, 10, 25, 35, 45, 5, 12, 22, 27 are inserted in this order into an empty BST. An iterative preorder traversal is then run: push the root; while the stack is non-empty, pop a node, visit it, push its right child (if any) and then its left child (if any). What is the largest number of nodes on the stack at any moment (measured after each iteration's pushes)?

  1. A. 3
  2. B. 6
  3. C. 5
  4. D. 4

Correct answer: C. 5

The tree: 50 (30, 80); 30 (20, 40); 80 (70, 90); 20 (10, 25); 40 (35, 45); 10 (5, 12); 25 (22, 27). Every time the traversal goes left it leaves the right sibling waiting on the stack. After popping 50: [80, 30]; 30: [80, 40, 20]; 20: [80, 40, 25, 10]; 10: [80, 40, 25, 12, 5] = 5 nodes, the maximum. (The inorder-style stack peaks at 5 for this tree, and pushing left before right gives 3.)

More Programming and Data Structures (GATE) questions

Exams that ask this topic