Created
February 11, 2016 21:31
-
-
Save kyle-dorman/accb6ffb77b6555c1202 to your computer and use it in GitHub Desktop.
Round 1 interview question, potential answer
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
/* | |
value String | |
children []Node | |
*/ | |
function Node(value, children) { | |
self.value = value; | |
self.children = children; | |
} | |
/* | |
root Node | |
*/ | |
function Tree(root) { | |
self.root = root; | |
/* | |
value String | |
depth Integer | |
node Node | |
*/ | |
var insertAt = function(value, depth, node) { | |
if (depth < 0) { | |
throw new Error(); | |
} else if (depth === 0) { | |
return new Node(value, [node]); | |
} else if (depth === 1) { | |
return new Node(node.value, [new Node(value, node.children)]); | |
} else { | |
var children = []; | |
for (var i = 0; i < node.children.length; i++) { | |
children += insertAt(value, depth - 1, node.children[i]); | |
} | |
return new Node(node.value, children); | |
} | |
} | |
} | |
/* | |
value String | |
depth Integer | |
*/ | |
Tree.prototype.insert = function(value, depth) { | |
self.root = insertAt(value, depth, self.root); | |
return self.root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment