-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Good Leaf Nodes Pairs.cpp
48 lines (47 loc) · 1.64 KB
/
Number of Good Leaf Nodes Pairs.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countPairs(TreeNode* root, int distance) {
unordered_map<TreeNode*, vector<TreeNode*>> map;
vector<TreeNode*> leaves;
findLeaves(root, {}, leaves, map);
int res = 0;
for (int i = 0; i < leaves.size(); i++) {
for (int j = i + 1; j < leaves.size(); j++) {
vector<TreeNode*>& list_i = map[leaves[i]];
vector<TreeNode*>& list_j = map[leaves[j]];
for (int k = 0; k < min(list_i.size(), list_j.size()); k++) {
if (list_i[k] != list_j[k]) {
int dist = list_i.size() - k + list_j.size() - k;
if (dist <= distance) res++;
break;
}
}
}
}
return res;
}
private:
void findLeaves(TreeNode* node, vector<TreeNode*> trail, vector<TreeNode*>& leaves, unordered_map<TreeNode*, vector<TreeNode*>>& map) {
if (!node) return;
vector<TreeNode*> tmp(trail);
tmp.push_back(node);
if (!node->left && !node->right) {
map[node] = tmp;
leaves.push_back(node);
return;
}
findLeaves(node->left, tmp, leaves, map);
findLeaves(node->right, tmp, leaves, map);
}
};