-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.ts
More file actions
39 lines (32 loc) · 639 Bytes
/
tree.ts
File metadata and controls
39 lines (32 loc) · 639 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
interface Node {
value: number;
children: Node[];
}
export default class Tree {
private root: Node;
constructor() {
this.root = null;
}
traverse(callback: Function): void {
function walk(node: Node) {
callback(node);
node.children.forEach(walk);
}
walk(this.root);
}
add(value: number, parentValue?: number): void {
const newNode: Node = {
value,
children: [],
};
if (this.root === null) {
this.root = newNode;
return;
}
this.traverse(node => {
if (node.value === parentValue) {
node.children.push(newNode);
}
});
}
}