forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0235.cpp
More file actions
37 lines (29 loc) · 814 Bytes
/
Copy path0235.cpp
File metadata and controls
37 lines (29 loc) · 814 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q){
if(!root)
return NULL;
if(root -> val == p -> val || root -> val == q -> val)
return root;
TreeNode* l = lca(root -> left, p, q);
TreeNode* r = lca(root -> right, p, q);
if(l && r)
return root;
else if(l)
return l;
else
return r;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return lca(root, p, q);
}
};