From the course: Data Structures in JavaScript: Trees and Graphs
Code a binary tree
From the course: Data Structures in JavaScript: Trees and Graphs
Code a binary tree
- [Narrator] Let's take a look at the JavaScript implementation for a binary tree. One way to represent a binary tree in JavaScript is to define a BinaryTreeNode class. We define a class with a constructor with three fields, this.val, this.left, and this.right. The left and right fields are nullable fields that can maintain a pointer to another binary tree node instance. The val can store any data on the node. Let's start by creating a binary tree that represents the tree we see here. We begin by instantiating the root node A, we then point the root node A's left to a new instance of the binary tree node class of the value B. This is how we create the relationship between root node A and the left child node B. We perform the identical operation for the root node A's right child of C. To create D, we can reference the node B through root.left and then add another .left and instantiate D there. We repeat the same operation for E through root.left.right. Finally, to create the node F and attach it to the tree, we need to access C, which is through root.right. Then we access C's right and create the node F there. In summary, we can define a binary tree node by defining a class that has properties, this.left and this.right and this.val. To form edges between nodes, we can simply assign the left or right of a node to another node to be the child node. Now that you understand how to represent a binary tree in JavaScript, we can move on to discuss common traversal algorithms.