forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Good Leaf Nodes Pairs.js
64 lines (56 loc) · 1.3 KB
/
Number of Good Leaf Nodes Pairs.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
let parentMap;
let leaves;
var countPairs = function(root, distance) {
if(root==null){
return 0;
}
leaves = [];
parentMap = new Map();
let cnt = 0;
let visited;
// Step1: build parent map
findParent(root, null);
// Step2: dfs to find all leafNodes
dfs1(root);
// Step3: count pairs from each leaf
for(const leaf of leaves)
{
visited = new Set();
cnt += dfs2(leaf, 0, distance, visited);
}
return cnt / 2;
};
function findParent(node, pa) {
if(node === null) {
return;
}
parentMap.set(node, pa);
findParent(node.left, node);
findParent(node.right, node);
}
function dfs1(node) {
if(node===null) {
return;
}
if(node.left===null && node.right === null) {
leaves.push(node);
return;
}
dfs1(node.left);
dfs1(node.right);
}
function dfs2(node, cur, dist, visited)
{
if(!node || cur > dist || visited.has(node) ) {
return 0;
}
if(node.left === null && node.right===null && cur !== 0) {
return 1;
}
visited.add(node);
let ans = 0;
ans += dfs2(parentMap.get(node), cur+1, dist, visited);
ans += dfs2(node.left, cur+1, dist, visited);
ans += dfs2(node.right, cur+1, dist, visited);
return ans;
}