36 lines
941 B
JavaScript
36 lines
941 B
JavaScript
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree
|
|
|
|
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
|
|
function Node(value) {
|
|
this.value = value;
|
|
this.left = null;
|
|
this.right = null;
|
|
}
|
|
function BinarySearchTree() {
|
|
this.root = null;
|
|
// Only change code below this line
|
|
this.add = (item) => {
|
|
const newNode = new Node(item);
|
|
if (this.root === null) {
|
|
this.root = newNode;
|
|
}
|
|
let parentNode = null;
|
|
let nodeBranch = "left";
|
|
let node = this.root;
|
|
while (node !== null) {
|
|
parentNode = node;
|
|
if (node.value == item) {
|
|
return null;
|
|
} else if (node.value < item) {
|
|
nodeBranch = "right";
|
|
node = node.right;
|
|
} else {
|
|
nodeBranch = "left";
|
|
node = node.left;
|
|
}
|
|
}
|
|
parentNode[nodeBranch] = newNode;
|
|
};
|
|
// Only change code above this line
|
|
}
|