Skip to content

Instantly share code, notes, and snippets.

@titarenko
Created February 1, 2018 13:24
Show Gist options
  • Select an option

  • Save titarenko/cc419c64f7db561a2aec28b6dd48b68b to your computer and use it in GitHub Desktop.

Select an option

Save titarenko/cc419c64f7db561a2aec28b6dd48b68b to your computer and use it in GitHub Desktop.
Binary Tree Item
class TreeItem {
constructor (item, getValue) {
this.item = item
this.value = getValue(item)
this.getValue = getValue
this.left = null
this.right = null
},
insert (item, position) {
if (position == null) {
return this.insert(
item,
this.value <= this.getValue(item) ? 'left' : 'right'
)
}
if (this[position] == null) {
this[position] = new TreeItem(item, this.getValue)
} else {
this[position].insert(item)
}
},
find (value, position) {
if (position == null) {
return this.find(
value,
this.value <= value ? 'left' : 'right'
)
}
return this[position] == null
? this.item
: this[position].find(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment