Created
March 13, 2019 01:58
-
-
Save dineshbalaji/a7498d5da5313056cb03b2b47888a888 to your computer and use it in GitHub Desktop.
Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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