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