Skip to content

Instantly share code, notes, and snippets.

@jaeming
Created November 8, 2017 06:37
Show Gist options
  • Save jaeming/296b85eb7c158abe1ac2d60df63a175f to your computer and use it in GitHub Desktop.
Save jaeming/296b85eb7c158abe1ac2d60df63a175f to your computer and use it in GitHub Desktop.
const Node = {
value: null,
parent: null,
left: null,
right: null,
create: function(props={}) {
let node = Object.create(this);
Object.keys(this).forEach( (key)=> {
node[key] = props[key] || this[key]
})
return node
},
add: function(node) {
if (!this.value) { this.createRoot(node) }
if (node.value < this.value) { this.addLeft(node) }
else if (node.value > this.value) { this.addRight(node) }
},
createRoot: function(node) {
this.value = node.value
},
addLeft: function(node) {
if (this.left) {
this.left.add(node)
} else {
this.left = node
}
},
addRight: function(node) {
if (this.right) {
this.right.add(node)
} else {
this.right = node
}
},
}
let root = Node.create({value: 109})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment