Skip to content

Commit b639b72

Browse files
authored
Merge pull request #24 from Bill0412/patch-5
Create 1740.Find-Distance-in-a-Binary-Tree_v2.cpp
2 parents 6879d33 + 7138bc1 commit b639b72

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
int lcaDepth = -1, pDepth, qDepth;
14+
TreeNode* lcaNode;
15+
int lowestCommonAncestor(TreeNode* root, int p, int q, int depth) {
16+
if(!root) return 0;
17+
18+
int count = lowestCommonAncestor(root->left, p, q, depth + 1) +
19+
lowestCommonAncestor(root->right, p, q, depth + 1) +
20+
(root->val == p) + (root->val == q);
21+
22+
if(root->val == p) pDepth = depth;
23+
if(root->val == q) qDepth = depth;
24+
if(count == 2 && lcaDepth == -1) lcaDepth = depth;
25+
26+
return count;
27+
}
28+
public:
29+
int findDistance(TreeNode* root, int p, int q) {
30+
lowestCommonAncestor(root, p, q, 0);
31+
32+
return (pDepth - lcaDepth) + (qDepth - lcaDepth);
33+
}
34+
};

0 commit comments

Comments
 (0)