-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursion_tree.js
86 lines (74 loc) · 2.01 KB
/
recursion_tree.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const tree =
{
id: 1,
label: 'tree 0',
children: [
{ id : 11, label : 'tree01', children: [
{id:111, label : 'tree111', children: []},
{id:112, label : 'tree1112', children: []}
]},
{ id : 12, label : 'tree01', children: [
{id:121, label : 'tree111', children: []},
{id:122, label : 'tree1112', children: []},
{id:123, label : 'tree1112', children: []}
]},
{ id:311, label : 'tree1112', children: []}
]};
const countNodes = (node) => {
let sum = 1;
if(node.children){
node.children.forEach(c => {
sum += countNodes(c);
});
}
return sum;
};
const treeCount = countNodes(tree);
console.log(`Tree Count ${treeCount}`);
// return all nodes with no branches
const getEndNode = (node) => {
let endNodes = [];
if(node.children && node.children.length > 0) {
node.children.forEach(child => {
const nodes = getEndNode(child);
endNodes = [...endNodes, ...nodes];
})
} else {
endNodes.push(node);
}
return endNodes;
};
const nodes = getEndNode(tree);
// Create tree.
const nodeRangeCount = 3;
const nodeCount = Math.ceil(Math.random() * nodeRangeCount);
let count = 0;
const createNodes = (node) => {
const child = {
level : node.level + 1,
children : []
};
let hasChildren = node.level === 0;
if(node.level < 6){
const rand = Math.ceil(Math.random() * nodeRangeCount);
hasChildren = rand > 1;
}
if(hasChildren){
const childCount = Math.ceil(Math.random() * nodeRangeCount);
for(let c = 0; c < childCount; c++){
child.id = node.level + '' + c;
const childNode = createNodes(child);
child.children.push(childNode);
}
} else {
child.id = node.level + '0'
}
if(child.children.length > 0){
console.log(count++ + ':' + child.children.length);
}
return child;
};
const rootNode = {id: 1, label : 'root', level: 0, children: []};
const deeptree = createNodes(rootNode, true);
const deepTreeNodecount = countNodes(deeptree);
console.log(deepTreeNodecount);