Question

Consider a complete binary tree with 7 nodes. Let AA denote the set of first 3 elements obtained by performing Breadth-First Search (BFS) starting from the root. Let BB denote the set of first 3 elements obtained by performing Depth-First Search (DFS) starting from the root.

The value of ∣A−B∣|A - B| is ______.

Official answer and solution
Official answer
1
From
Official GATE 2021 answer key

Solution

Determine the set of nodes visited in the first three steps of BFS and DFS on a complete binary tree of 7 nodes.

Consider a 7-node complete binary tree labeled in level order:

  • Root: 1
  • Level 1: Left child 2, Right child 3
  • Level 2: Children of 2 are 4 and 5; children of 3 are 6 and 7.

BFS visits nodes level by level:

  • Step 1: node 1 (root)
  • Step 2: node 2 (first child in level 1)
  • Step 3: node 3 (second child in level 1)
    Thus, the set of the first 3 elements visited by BFS is A={1,2,3}A = \{1, 2, 3\}.

DFS explores deeply along a branch first:

  • Starting from root 1, it visits child 2, and then proceeds to the child of 2 (node 4 or 5).
  • Thus, the set of first 3 elements visited by DFS is B={1,2,4}B = \{1, 2, 4\} (or {1,2,5}\{1, 2, 5\} if right child visited first, or {1,3,6}/{1,3,7}\{1, 3, 6\} / \{1, 3, 7\} if right subtree explored first).

In any standard DFS traversal:

  • Root 1 is in both AA and BB.
  • Exactly one child of the root (node 2 or node 3) is visited in the first 3 steps, and the third node visited in DFS is a grandchild (from level 2).
  • Therefore, A∩BA \cap B contains exactly 2 nodes (the root and one child), while the other child of the root is in AA but not in BB.

Consequently, ∣A−B∣=3−2=1|A - B| = 3 - 2 = 1.

Final answer

1

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
Question
26 of 65, printed as CS Q.16
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.