Created
January 26, 2020 11:31
-
-
Save dmitry-vsl/4c32534ad16ba400e43144b3d0ea515e to your computer and use it in GitHub Desktop.
Simple TreeMap (no balancing)
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 TreeMap { | |
constructor(){ | |
this.root = null | |
} | |
get(key){ | |
return this.doGet(key, this.root) | |
} | |
doGet(key, current){ | |
if(current == null){ | |
return null | |
} | |
if(current.key == key){ | |
return current.value | |
} | |
return this.doGet(key, current.key < key ? current.right : current.left) | |
} | |
set(key, value, current){ | |
if(this.root == null){ | |
this.root = {key, value} | |
} else { | |
this.doSet(key, value, this.root) | |
} | |
} | |
doSet(key, value, current){ | |
if(current.key == key){ | |
current.value = value | |
} else if(current.key < key){ | |
if(current.right == null){ | |
current.right = {key, value} | |
} else { | |
this.doSet(key, value, current.right) | |
} | |
} else { | |
if(current.left == null){ | |
current.left = {key, value} | |
} else { | |
this.doSet(key, value, current.left) | |
} | |
} | |
} | |
list(){ | |
var result = [] | |
this.doList(result, this.root) | |
return result | |
} | |
doList(result, current){ | |
if(current == null){ | |
return | |
} | |
this.doList(result, current.left) | |
result.push({key: current.key, value: current.value}) | |
this.doList(result, current.right) | |
} | |
} | |
var map = new TreeMap() | |
map.set(3, 'three') | |
map.set(7, 'seven') | |
map.set(1, 'one') | |
map.set(2, 'two') | |
map.set(0, 'zero') | |
map.set(10, 'ten') | |
map.set(9, 'nine') | |
console.log(map.list()) | |
console.log(map.get(9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment