JSFiddle - React, Tailwind, and code Playground
by Anjana Silva
TypeScript
class BinarySearchTree {
private root: TreeNode;
public getRoot (): TreeNode {
return this.root;
}
public setRoot (root: TreeNode) {
this.root = root;
}
constructor () {
this.root = null;
}
/*
* Takes a numeric value add add to the current tree.
* @param value numeric value
* @returns Returns boolean true or false
*/
public addToTree(value: number) : boolean {
// Create new node
const newNode = new TreeNode(value);
// If tree is empty, set new node as the root
if (this.root == null) {
this.root = newNode;
} else {
// Tree is not empty, so find the right spot for the new node
let currentNode = this.root;
let traversing = true;
while (traversing) {
// Duplicates are not allowed
if (currentNode.value === newNode.value) {
traversing = false;
return false;
} else if (newNode.value < currentNode.value) {
// Traversing left of the node
if (currentNode.left == null) {
currentNode.left = newNode;
traversing = false;
return true;
} else {
// Traversing left of the current node
currentNode = currentNode.left;
}
} else if (newNode.value > currentNode.value) {
// Traversing right of the current node
if (currentNode.right == null) {
currentNode.right = newNode;
traversing = false;
return true;
} else {
// Traversing right of the current node
currentNode = currentNode.right;
}
}
...