-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc1740
47 lines (38 loc) · 1.07 KB
/
lc1740
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
46
47
class Solution {
public:
int findDistance(TreeNode* root, int p, int q) {
TreeNode* theNode = lca(root,p,q);
int left = findDist(theNode,p,0);
int right = findDist(theNode,q,0);
return left + right;
}
int findDist(TreeNode* parent, int target,int dist) {
if(parent==NULL)
return 0;
if(parent->val==target)
return dist;
int left = findDist(parent->left,target,1+dist);
int right = findDist(parent->right,target,1+dist);
return max(left,right);
}
TreeNode* lca(TreeNode*root, int p, int q) {
if(!root) {
return NULL;
}
if(root->val == p || root->val ==q) {
return root;
}
TreeNode* left = lca(root->left,p,q);
TreeNode* right =lca(root->right, p ,q);
if(left && right) {
return root;
}
if(left) {
return left;
}
if(right) {
return right;
}
return NULL;
}
};