-
Notifications
You must be signed in to change notification settings - Fork 0
/
leafNodePairs.txt
36 lines (32 loc) · 1.23 KB
/
leafNodePairs.txt
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
1530. Number of Good Leaf Nodes Pairs
You are given the root of a binary tree and an integer distance.
A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path
between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
class Solution {
public:
int countPairs(TreeNode* root, int distance) {
int res = 0;
dfs(root, distance, res);
return res;
}
vector<int> dfs(TreeNode* root, int distance, int& res) {
if (!root->left && !root->right) return {1};
vector<int> left, right;
if (root->left) left = dfs(root->left, distance, res);
if (root->right) right = dfs(root->right, distance, res);
for (int i = 0; i < left.size(); ++i) {
for (int j = 0; j < right.size(); ++j) {
if (left[i] + right[j] <= distance) ++res;
}
}
vector<int> res_vec;
for (int i = 0; i < left.size(); ++i) {
if (left[i] + 1 < distance) res_vec.push_back(left[i] + 1);
}
for (int i = 0; i < right.size(); ++i) {
if (right[i] + 1 < distance) res_vec.push_back(right[i] + 1);
}
return res_vec;
}
};