[LeetCode] Number of Good Leaf Nodes Pairs

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.

  • huffman encoding solution
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
/**
* 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 {
vector<string> code;
void helper(TreeNode* node, string c) {
if(!node) return;
if(!node->left and !node->right) {
code.push_back(c);
} else {
helper(node->left, c + '0');
helper(node->right, c + '1');
}
}
int distance(string& c1, string& c2) {
int n = c1.length(), m = c2.length();
if(n < m) return distance(c2, c1);

int diff = n - m;
int i = 0;
while(i < m and c1[i] == c2[i]) i++;
return (n - i) * 2 - diff;
}
public:
int countPairs(TreeNode* root, int dis) {
helper(root, "");
int res = 0, n = code.size();
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++) {
if(distance(code[i], code[j]) <= dis){
res++;
}
}

return res;
}
};
  • prefix sum solution
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
/**
* 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 {
int sum = 0;
vector<int> helper(TreeNode* node, int& distance) {
vector<int> res(distance + 1, 0);
if(!node) return res;
if(!node->left and !node->right) {
res[1] = 1;
return res;
}
auto l = helper(node->left, distance);
auto r = helper(node->right, distance);

int psum = accumulate(begin(l), end(l), 0);
for(int i = 0; i <= distance; i++) {
sum += psum * r[i];
psum -= l[distance - i];
}


for(int i = 0; i < distance; i++)
res[i + 1] = l[i] + r[i];
return res;
}
public:
int countPairs(TreeNode* root, int distance) {
helper(root, distance);

return sum;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/24/PS/LeetCode/number-of-good-leaf-nodes-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.