Created
October 9, 2018 12:53
-
-
Save justinobney/839ca5f7e5973893b9d56ebc9078fdc6 to your computer and use it in GitHub Desktop.
bst
This file contains hidden or 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 Node { | |
| constructor(value){ | |
| this.value = value; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| insert(value){ | |
| if(value < this.value){ | |
| if(!this.left){ | |
| this.left = new Node(value); | |
| } else { | |
| this.left.insert(value) | |
| } | |
| } else { | |
| if(!this.right){ | |
| this.right = new Node(value); | |
| } else { | |
| this.right.insert(value) | |
| } | |
| } | |
| } | |
| get(value){ | |
| if(this.value === value){ | |
| return this.value; | |
| } else if(this.left && value <= this.value){ | |
| return this.left.get(value); | |
| } else if(this.right && value >= this.value) { | |
| return this.right.get(value); | |
| } else { | |
| console.log(value); | |
| } | |
| } | |
| } | |
| class Tree { | |
| insert(value){ | |
| if(!this.root){ | |
| this.root = new Node(value); | |
| } else { | |
| this.root.insert(value); | |
| } | |
| } | |
| get(value){ | |
| return this.root.get(value); | |
| } | |
| } | |
| const tree = new Tree(); | |
| tree.insert(15); | |
| tree.insert(35); | |
| tree.insert(30); | |
| tree.insert(37); | |
| tree.insert(38); | |
| tree.insert(39); | |
| tree.insert(45); | |
| tree.insert(20); | |
| tree.insert(27); | |
| tree.insert(28); | |
| tree.insert(22); | |
| tree.insert(40); | |
| tree.insert(25); | |
| console.log(tree.get(45)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment