Created
November 8, 2017 06:37
-
-
Save jaeming/296b85eb7c158abe1ac2d60df63a175f to your computer and use it in GitHub Desktop.
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
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