liveBook · Manning

Preorder traversal

As explained in Functional Programming in JavaScript

A tree traversal strategy that visits a node before recursively visiting its children.

Preorder traversal visits a tree node before recursively visiting its children. Starting at the root, it processes the current value, descends through the left subtree, then processes the right subtree. section 3.5

The traversal follows three steps:

Mapping a mathematician tree

A Node tree links Church to descendants such as Rosser, Turing, and Kleene. Tree.map(church, p => p.fullname) applies the function during preorder traversal, producing names beginning with Alonzo Church, followed by Barkley Rosser and its children, then the remaining branches. section 3.5

class Tree {
   constructor(root) {
      this._root = root;
   }
   static map(node, fn, tree = null) {                     #1
      node.value = fn(node.value);                         #2
      if(tree === null) {
          tree = new Tree(node);                           #3
      }
      if(node.hasChildren()) {                             #4
        _.map(node.children, function (child) {            #5
            Tree.map(child, fn, tree);                     #6
        });
      }
      return tree;
   }
       get root() {
          return this._root;
       }
   }

Inspect the recursive Tree.map implementation: it transforms the current node, creates the result tree, and recursively maps over each child. section 3.5

How Functional Programming in JavaScript covers it

How deep it goes
Defines the visit order, illustrates recursive descent, and implements it through Tree.map.
Examples
Uses a mathematician hierarchy represented with Node objects and mapped to a preorder sequence of full names.
What it assumes
Builds from root nodes, parent-child links, child collections, and recursively defined trees.
What you can do after
Apply it via recursive JavaScript functions that process or transform each tree node in preorder.
How it connects
Connects trees with recursion, higher-order functions, mapping, immutability, and side-effect-free data transformation.

Also explained in

Compare how 2 books explain preorder traversal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.