1530. Number of Good Leaf Nodes Pairs
/**
* 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 cnt = 0;
vector<int> dfs(TreeNode* root, int distance) {
vector<int> V;
if(!root) return V;
if(!root->left && !root->right) {
V.push_back(0);
return V;
}
auto left_V = dfs(root->left, distance);
auto right_V = dfs(root->right, distance);
for(int ii = 0; ii < left_V.size(); ii++) left_V[ii]++;
for(int ii = 0; ii < right_V.size(); ii++) right_V[ii]++;
for(int ii = 0; ii < left_V.size(); ii++) {
for(int jj = 0; jj < right_V.size(); jj++) {
if(left_V[ii] + right_V[jj] <= distance) cnt++;
}
}
left_V.insert(left_V.end(), right_V.begin(), right_V.end());
return left_V;
}
int countPairs(TreeNode* root, int distance) {
dfs(root, distance);
return cnt;
}
};