Skip to content

Instantly share code, notes, and snippets.

@dineshbalaji
Created March 13, 2019 01:58
Show Gist options
  • Save dineshbalaji/a7498d5da5313056cb03b2b47888a888 to your computer and use it in GitHub Desktop.
Save dineshbalaji/a7498d5da5313056cb03b2b47888a888 to your computer and use it in GitHub Desktop.
Binary Tree
class BinaryTree {
constructor(value) {
// preparing root element
this.value = value;
this.left = null;
this.right = null;
}
add(value) {
if (value < this.value) {
// add as left node
if(this.left) {
this.left.add(value);
} else {
this.left = new BinaryTree(value);
}
} else {
// add as right node
if(this.right) {
this.right.add(value);
} else {
this.right = new BinaryTree(value);
}
}
return this; // for chaining funcation call;
}
}
let root = new BinaryTree(5);
root.add(3).add(8).add(2).add(4).add(7).add(9)
window.root= root;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment