liveBook · Manning

Tree

As explained in Functional Programming in JavaScript

A hierarchical data structure of nodes connected by parent-child relationships with a root.

A tree organizes data into nodes linked by parent-child relationships. One node serves as the root; each branch repeats the same structure, making recursion a natural way to process the whole hierarchy. section 3.5

A JavaScript tree

A Node stores a value, a parent, and an array of children. append connects a child to its parent, so a hierarchy can be assembled fluently: church.append(rosser).append(turing).append(kleene); kleene.append(nelson).append(constable); rosser.append(mendelson).append(sacks); turing.append(gandy). Tree.map can then recursively apply a function to every node, such as Tree.map(church, p => p.fullname). section 3.5

A recursive tree operation follows a simple pattern:

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, which transforms a node and descends through its children. section 3.5

How Functional Programming in JavaScript covers it

How deep it goes
Defines roots, parents, children, nodes, and recursive mapping with JavaScript classes.
Examples
Uses a mathematician student hierarchy, chained append calls, and recursive name mapping.
What it assumes
Introduces recursive thinking through array summation before applying it to tree-shaped data.
What you can do after
Builds a JavaScript tree and recursively transforms every node.
How it connects
Connects trees with recursion, functional programming, and preorder traversal.

Also explained in

Compare how 11 books explain tree →

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.