[LeetCode] Find Distance in a Binary Tree

1740. Find Distance in a Binary Tree

Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.

The distance between two nodes is the number of edges on the path from one to the other.

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
/**
* 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 res = -1;
pair<int, bool> helper(TreeNode* node, int p, int q, int level) {
if(!node or res != -1) return {-1, false};
if(node->val == p or node->val == q) {
auto [ll, lf] = helper(node->left, p, q, level + 1);
auto [rl, rf] = helper(node->right, p, q, level + 1);
if(lf) {
res = ll - level;
return {-1, false};
} else if(rf) {
res = rl - level;
return {-1, false};
} else return {level, true};
} else {
auto [ll, lf] = helper(node->left, p, q, level + 1);
auto [rl, rf] = helper(node->right, p, q, level + 1);
if(lf and rf) {
res = ll + rl - 2 * level;
return {-1, false};
} else if(lf) return {ll, lf};
else if(rf) return {rl, rf};
return {-1, false};
}
}
public:
int findDistance(TreeNode* root, int p, int q) {
if(p == q) return 0;
helper(root, p, q, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/LeetCode/find-distance-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.