Question
Consider a complete binary tree with 7 nodes. Let denote the set of first 3 elements obtained by performing Breadth-First Search (BFS) starting from the root. Let denote the set of first 3 elements obtained by performing Depth-First Search (DFS) starting from the root.
The value of 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 .
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 (or if right child visited first, or if right subtree explored first).
In any standard DFS traversal:
- Root 1 is in both and .
- 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, contains exactly 2 nodes (the root and one child), while the other child of the root is in but not in .
Consequently, .
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.