Skip to content

Commit 3d112ba

Browse files
Update code solution
1 parent a0e6de5 commit 3d112ba

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Intuition
2+
The idea is to first get the path to each leaf node.
3+
Then, compare each leaf path with every other leaf path to calculate the distance between them.
4+
Complexity
5+
Time complexity: O(n
6+
2
7+
⋅logn)
8+
Space complexity: O(n⋅h)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution
13+
{
14+
public:
15+
void getPath(TreeNode *root, vector<string> &path, string &st)
16+
{
17+
if (!root)
18+
return;
19+
if (!root->left && !root->right)
20+
path.push_back(st);
21+
if (root->left)
22+
{
23+
st += 'l';
24+
getPath(root->left, path, st);
25+
st.pop_back();
26+
}
27+
if (root->right)
28+
{
29+
st += 'r';
30+
getPath(root->right, path, st);
31+
st.pop_back();
32+
}
33+
}
34+
int countPairs(TreeNode *root, int distance)
35+
{
36+
int ans = 0;
37+
vector<string> path;
38+
string st = "";
39+
getPath(root, path, st);
40+
for (int i = 0; i < path.size(); i++)
41+
{
42+
for (int j = i + 1; j < path.size(); j++)
43+
{
44+
int k = 0;
45+
int tmp = 0;
46+
while (k < path[i].size() && k < path[j].size())
47+
{
48+
if (path[i][k] != path[j][k])
49+
break;
50+
k++;
51+
}
52+
tmp += path[i].size() - k + path[j].size() - k;
53+
if (tmp <= distance)
54+
ans++;
55+
}
56+
}
57+
return ans;
58+
}
59+
};

0 commit comments

Comments
 (0)