>> Object { value: 1, done: false }
>> Object { value: 2, done: false }
Earlier this year, I was interviewing for frontend engineering positions and tree questions were very popular. After repetitively solving tree recursion problems and trying to improve my tactics, I came across a novel JavaScript feature – Generators – that makes tree recursion as easy as array iteration.
Why do we even need Generators? To put it bluntly, implementing the Iteration protocols for an object or a class is a PITA. With generators, we get a concise syntax that makes it easy to implement the Iteration protocols – which we’ll leverage later on to simplify tree recursion into iteration.
A complete explanation of Generators is beyond the scope of this article but it’s important to understand a few basics of the syntax to understand the following exercises.
yield
multiple values
whereas a regular function can only return a single value.function*
syntax allows us to define a function that will return a
Generator, and the yield
syntax allows us to return the next value from
inside of a Generator.for...of
loops.For example, here’s a function that returns a Generator for and infinite series of numbers. Notice that this function will never terminate but by wrapping it in a Generator we can pause and restart it whenever we want.
|
|
>> Object { value: 1, done: false }
>> Object { value: 2, done: false }
For all of the exercises below, we’ll be using the tree above to illustrate each
type of traversal. The tree above was created by using a helper function called
createTreeNode
which accepts a single value and an array of children.
|
|
Every single tree question that I was given involved depth-first traversal. For example, flatten an array of trees, search the DOM for elements with a specific class name, or build a recursive React component.
|
|
1
2
3
4
5
6
I was never asked any questions that required breadth-first traversal but I’m including this exercise because it shows the versatility of this technique. For example, print the values of a tree in row order.
|
|
1
2
5
3
4
6
I encountered backtracking once as an extension to a depth-first tree traversal question. For example, search the DOM for leaf elements with a specific hierarchy of class names.
|
|
6
5
1
Hopefully, I’ve made a strong case that tree recursion can be as easy as array iteration by using JavaScript Generators. All of the source code for this blog post is available on GitHub.