Rubrik logoRubrik
CodingFree preview

Tree Traversal Validation

Build a tree from paired edge arrays and determine whether each candidate ordering can be a valid BFS traversal.

SWE
tree
bfs
Frequency
Single report
Last asked
2026-02-04
Stage
oa

Requirements

  • Input: two equally sized vectors; values at the same index define an edge. The edges form a tree.
  • Input also includes queries, each containing as many values as the tree has nodes.
  • For each query, determine whether it is a valid FIFO breadth-first traversal of the tree.
  • Account for the possible processing order of nodes at the same traversal level.

Examples

vec1 = [1,1,4], vec2 = [3,2,3] form a tree with root 1, children 3 and 2, and node 4 below 3. Query [1,2,3,4] is valid.

Notes

The example uses root 1. Clarify the root-selection rule and output-container convention for the general case before coding.

For a fixed root, orient the tree into parent and child relationships once. Each query must contain every node exactly once and begin with that root; reject duplicates, missing nodes, and unknown labels before simulation.

Use a FIFO queue initialized with the root and a pointer just after the query's first entry. Pop a parent with c children: the next c query entries must be exactly its children, in any order. Compare the block with the child set, enqueue that block in query order, and advance the pointer by c. Reject a mismatch; accept only after the queue is empty and all entries are consumed. A parent's children enter the queue together, so checking only nondecreasing depth would incorrectly allow some interleavings between different parents.

With hash sets, rooting takes O(N) time and space, and validation takes expected O(N) time per query with O(N) working space. Reuse the rooted structure across queries only when the root stays fixed. These bounds assume constant-time node hashing; ordered sets change the bound.

Preparation

  • In 20 minutes, implement a traversal validator with an explicit root parameter and test valid sibling permutations, duplicates, missing nodes, and a wrong starting node.
  • In 10 minutes, construct a tree with two parents on one level and show why interleaving their children can fail despite nondecreasing depths.
Was this article helpful?

Comments

Sign in to join the discussion
Loading...