Walk a Tree with Generators
Write the code, see it run, pass the checks.
The problem
- medium
- Code
A tree is made of nodes like { value, children }, where children is an array of nodes and may be missing on a leaf. Write two generator functions that yield the values of every node, starting from a root node. depthFirst(root) yields a node's value, then everything in its first child's subtree, then its second child's, and so on. breadthFirst(root) yields the root's value, then the values of its children from left to right, then all their children, level by level. Both read a node's children only when they need to, so taking the first few values works even on an endless tree whose children are made as they're read.
Your code must pass
- Walks depth-first, parent before children
- Walks breadth-first, level by level
- Handles leaves without a children array
- Works on an endless tree