2dbi

Binary tree traversal (BFS/DFS)

viaGlassdoor

Problem A basic binary-tree problem (easy) solvable with either BFS (level-order) or DFS — for example computing depth, returning level-order values, or checking a path property.

Input / Output

  • Input: the root of a binary tree.
  • Output: the requested property (e.g. maximum depth, list of level values, or a boolean).

Constraints

  • Up to ~10^4 nodes; a single pass is expected.

Example

  • For a tree of height 3, a level-order traversal returns node values grouped by depth.

Expected approach

  • BFS with a queue for level-order, or DFS via recursion/stack. O(n) time, O(n) space. Communicating the approach clearly is emphasised.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account