-
Notifications
You must be signed in to change notification settings - Fork 3
/
235.cpp
31 lines (28 loc) · 926 Bytes
/
235.cpp
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
/**
* 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* dfs(TreeNode* node, TreeNode* p, TreeNode* q) {
if (node == nullptr) return nullptr;
if (node == p) return node;
if (node == q) return node;
TreeNode* left = nullptr;
if (node->val > p->val || node->val > q->val) left = dfs(node->left, p, q);
TreeNode* right = nullptr;
if (node->val < p->val || node->val < q->val) right = dfs(node->right, p, q);
if (left && right) return node;
else if (left) return left;
else if (right) return right;
else return nullptr;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return dfs(root, p, q);
}
};