-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathDay-112.cpp
More file actions
29 lines (29 loc) · 762 Bytes
/
Day-112.cpp
File metadata and controls
29 lines (29 loc) · 762 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
/**
* 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr){
return nullptr;
}
if(root->val == p->val || root->val == q->val){
return root;
}
auto t1 = lowestCommonAncestor(root->left , p , q);
auto t2 = lowestCommonAncestor(root->right , p , q);
if(t1 != nullptr && t2 != nullptr){
return root;
}else if(t1 != nullptr){
return t1;
}else{
return t2;
}
}
};