Trees

Let’s create our template for nodes. Nodes can be either the “root” (top of the tree or section of a tree) or a “leaf” (child of another node).

function Node (value) {
  this.value=value;
  this.left=null;
  this.right=null;
}

This is an example of the definition of a tree node. You can create a tree data structure in many different ways, it’s more about the representation of a tree than the exact specifics of how you do it. The above definition when called creates a new object with initial value set to the input parameter, and no children.

let root=new Node(2);
let left=new Node(1);
let right=new Node(4);
root.left=left;
root.right=right;
console.log(root);
Result:
Node {
   value: 2,
   left: Node { value: 1, left: null, right: null },
   right: Node { value: 4, left: null, right: null }
}

We create 3 node objects, with initial values of 2, 1, and 4 respectively. Then we assign the 2nd and 3rd node to be the children of the first node.
You can now think of root as the top of the tree, and the subsequent nodes as children of that tree.
If you look at the output from console logging root, you can see that the val property of the object is 2. The left and right properties are themselves Nodes, with values 1 and 4 and no children. You can create children for those nodes in a similar manner.