FrontendInterviews.dev

Loading problem…

6. Find All Reachable Nodes in Tree

Medium•
Acceptance: 74.29%
•
🔓3/3 Pro unlocks today

You're building a file system explorer that needs to list all files and folders accessible from a root directory.

Given the root of an N-ary tree, return all reachable node values in level-order (BFS).

Level-order means:

  • Visit the root first
  • Then visit nodes level by level
  • Within the same level, preserve children order as provided in node.children

> Note: A DFS traversal can reach all nodes, but it will produce a different order for many test cases.

Requirements

1. Basic Functionality

  • Find all nodes reachable from root
  • Handle trees with any number of children
  • Return values in level-order (BFS)
  • Handle empty tree (return empty array)

Example Usage

// Tree structure:
//       1
//     / | \
//    2  3  4
//   /|  |
//  5 6  7

findReachableNodes(root);
// [1, 2, 3, 4, 5, 6, 7]
// BFS level-order output

Real-World Context

This problem models practical tree traversal scenarios:

  • File system: List entries by folder depth
  • Navigation trees: Build breadth-first menu structures
  • Access control: Enumerate reachable resources from a root

Constraints

  • The number of nodes in the tree is in the range [0, 1000]
  • -1000 <= Node.val <= 1000
  • Tree may have any number of children per node
  • Return values in level-order (BFS)