Last active
February 14, 2017 21:14
-
-
Save mr-rob0to/374fb1c8532a49f22fd6383e2625b9f9 to your computer and use it in GitHub Desktop.
Binary Search Tree (Ordered Map)
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 BST { | |
constructor(key, value, parent) { | |
this.key = key || null; | |
this.value = value || null; | |
this.parent = parent || null; | |
this.left = null; | |
this.right = null; | |
} | |
insert(key, value, parent) { | |
if (this.key === null) { | |
this.key = key; | |
this.value = value; | |
} | |
else if (key < this.key) { | |
if (this.left === null) { | |
this.left = new BST(key, value, this); | |
} else { | |
this.left.insert(key, value); | |
} | |
} | |
else { | |
if (this.right === null) { | |
this.right = new BST(key, value, this); | |
} | |
else { | |
this.right.insert(key, value); | |
} | |
} | |
} | |
get(key) { | |
if (this.key === key) { return this.value } | |
else if (key < this.key && this.left) { | |
return this.left.get(key); | |
} | |
else if (key > this.key && this.right) { | |
return this.right.get(key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment