Implement a Binary Search Tree
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Description
Let's implement a Binary Search Tree! Recall that a binary search tree, or a BST, is a binary tree that is ordered via these two properties:
- The left sub-tree of a node has a value less than or equal to its parent node's value.
- The right sub-tree of a node has a value greater than to its parent node's value.

Given the following tree node definition:
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
Can you fill out the skeleton code and implement a binary search tree with #add and #remove methods?
class BST {
constructor(val) {
this.root = new Node(val);
}
add(val) {
// fill this in
}
remove(val) {
// fill this in
}
}
Constraints
- Maximum number of nodes <=
1000 - Value of each node can lie between
-1000000000and1000000000 - Expected time complexity for most BST operations (including search, insert, and delete) is
O(log n)wherenbeing the number of nodes - Expected space complexity :
O(n)
```js
class BST {
constructor(val) {
this.root = new Node(val);
}
add(val) {
// fill this in
}
remove(val) {
// fill this in
}
}
// const bst = new BST(4);
// bst.add(3);
// bst.add(5);
// console.log(bst.root.left.val === 3);
// console.log(bst.root.right.val === 5);
```
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →