Skip to content

Traversal

Webber Wang edited this page Sep 20, 2020 · 1 revision

Traversing a Tree is as simple as visiting each Node & doing some operation on the Node. There are 2 types of operations, mapping & reducing. Mapping allows us to transform from 1 Tree to another Tree, while reducing gives us a final object. Like the example in Home, we can map from JSON tree to React DOM tree, or we can reduce a Tree to a number containing the total node count.

Traversal is a recursive program that calls the same function with the children nodes passed in. When there are no more children, the recursive function returns and goes back up the tree.

There are 3 types of traversal order for a tree, InOrder, PreOrder and PostOrder. We use PostOrder since that returns the nodes from the Leaf up to the Root, this is required when building a React tree.

During Traversal, the Iteratee callback function is called for each Node, and returns some transformation. For each different kind of product, we can keep the same Traversal function, and just pass in a different kind of Iteratee.

The Iteratee can also be thought of as a Factory function. Each Node may have a different type, and the type will be passed as parameter to the Iteratee/Factory function to produce the corresponding product.

We use type guards in the Factory functions to tell it what to product.

Clone this wiki locally