Skip to content

Instantly share code, notes, and snippets.

@ronakjain2012
Created August 1, 2022 17:31
Show Gist options
  • Save ronakjain2012/31bf6499669caeda80c10cc4050cc1c6 to your computer and use it in GitHub Desktop.
Save ronakjain2012/31bf6499669caeda80c10cc4050cc1c6 to your computer and use it in GitHub Desktop.
Ternary Binary Tree Implementation in JavaScript
class Node {
constructor(char) {
this.char = char;
this.right = this.left = this.middle = this.eow = null;
}
}
class TST {
constructor() {
this.root = null;
}
add(word) {
let newNode;
if (this.root == null) {
this.addNode(newNode, word, 0);
} else {
this.addNode(this.root, word, 0);
}
}
addNode(root, str, index) {
if (root == null) {
root = new Node(str[index]);
if (this.root == null) {
this.root = root;
}
}
console.log(index, str.length - 1);
if (index < str.length - 1) {
if (str[index] < root.char) {
root.left = this.addNode(root.left, str, index);
} else if (str[index] > root.char) {
root.right = this.addNode(root.right, str, index);
} else {
root.middle = this.addNode(root.middle, str, index + 1);
}
} else root.eow = true;
return root;
}
}
(() => {
let tree = new TST();
tree.add("Hey!!");
tree.add("He");
tree.add("Hey!! I am Ronak Bokaria");
tree.add("Hey!! I have your notebook");
console.log(tree);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment