-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.cpp
More file actions
39 lines (35 loc) · 921 Bytes
/
code.cpp
File metadata and controls
39 lines (35 loc) · 921 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
38
39
// This is for the leetcode version of the problem
/**
* 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 == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr) {
return root;
}
else if (left != nullptr) {
return left;
}
else if (right != nullptr) {
return right;
}
else {
return nullptr;
}
}
};