Last active
January 21, 2016 20:38
-
-
Save saml/a8556d5fcfa0947f35d3 to your computer and use it in GitHub Desktop.
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
class Thing { | |
constructor(public id: number, public parentId: number) { | |
} | |
} | |
/* | |
1 | |
/ \ | |
2 3 | |
/ / \ | |
4 5 6 | |
/ | |
7 | |
*/ | |
const nodes: Thing[] = [ | |
new Thing(1, -1), | |
new Thing(2, 1), | |
new Thing(3, 1), | |
new Thing(4, 2), | |
new Thing(5, 3), | |
new Thing(6, 3), | |
new Thing(7, 5) | |
]; | |
class TreeNode<T> { | |
constructor(public value: T, public children: TreeNode<T>[]) { | |
} | |
find(x: T): TreeNode<T> { | |
if (this.value == x) { | |
return this; | |
} | |
for (let i = 0; i < this.children.length; i++) { | |
const found: TreeNode<T> = this.children[i].find(x); | |
if (found) { | |
return found; | |
} | |
} | |
return null; | |
} | |
} | |
function insert(tree: TreeNode<number>, thing: Thing): TreeNode<number> { | |
const parentNode: TreeNode<number> = tree.find(thing.parentId); | |
if (parentNode) { | |
parentNode.children.push(new TreeNode(thing.id, [])); | |
} | |
return tree; | |
} | |
console.log(nodes.reduceRight(insert, new TreeNode(-1, []))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment