Node in Javascript


Each element in a tree is a node. We need to define a node before we proceed to define a binary tree as a tree consists of nodes. We'll create a very simple node definition that has 3 properties, namely: left, right and data.

  • left − This holds the reference to the left child of this node.

  • right − This holds the reference to the right child of this node.

  • data − This holds the reference to the data we want to store in this node.

Let us see the code representation of such a structure.

Examle

class Node {
   constructor(data, left = null, right = null) {
      this.data = data;
      this.left = left;
      this.right = right;
   }
}

We've defined the Node data structure with a constructor that takes 3 properties, data left and right. We'll mostly just create a node with null left and right properties as we'll be inserting values at leaves.

For ease of use, we'll define Node as a property of the BinarySearchTree class that we'll create in order to keep this class within the place we use it.

Note that such nodes with 2 explicit left and right properties are needed for binary trees. For multiway trees like B trees or B+ trees, we define a property called children which is an array (or some other container like data structure).

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 15-Jun-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements