-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtree.js
79 lines (61 loc) · 1.35 KB
/
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
class Node {
constructor(value) {
this.value = value;
this.children = [];
}
}
// const current_level = parent_level + 1;
const listNodesAtLevel = (root, level) => {
const list = [];
const queue = [];
};
//can do via bfs too
const countSum = root => {
if (root === null) {
return 0;
}
let sum = 0;
const { children } = root;
sum = sum + root.value;
for (let index = 0; index < children.length; index++) {
sum += countSum(children[index]);
}
return sum;
};
const leavesCount = root => {
if (root === null) return 0;
let count = 0;
const { children } = root;
if (children.length === 0) return 1;
for (let index = 0; index < children.length; index++) {
count += leavesCount(children[index]);
}
return count;
};
const leavesCountBfs = root => {
const queue = [];
let leavesCount = 0;
queue.push(root);
while (queue.length) {
const front = queue.shift();
const { children } = front;
if (children.length === 0) {
leavesCount++;
} else {
children.forEach(child => {
queue.push(child);
});
}
}
return leavesCount;
};
const root = new Node(2);
const children = [];
const one = new Node(3);
const two = new Node(4);
const three = new Node(5);
children.push(one);
children.push(two);
children.push(three);
root.children = children;
console.log(countSum(root));