From the course: Data Structures in JavaScript: Trees and Graphs

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Binary search tree implementation: insert

Binary search tree implementation: insert

- [Instructor] Now that we understand a BST conceptually, let's code one up in JavaScript. We'll implement the core operations of a BST, including search, insertion, and deletion. Let's start by creating the basic structure for a binary tree. First, we'll define a tree node class. (instructor typing) Each node will store a value and references to its left and right children. Now let's define the binary search tree class. (instructor typing) This class will manage the overall tree, and include insertion, searching, and deletion methods. For debugging purposes, I'm going to paste a print method that will print in order the BST to ensure that order is maintained. If the numbers are in an ascending order, when printing an order, we know that the constraints of the BST are maintained. The insert method takes in a value and inserts it into the BST. We'll iteratively walk down from the root, choosing left or right at each node, based on comparisons, and inserting when a null child is found…

Contents