-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlowestCommonAncestor_236.cpp
More file actions
58 lines (54 loc) · 1.52 KB
/
Copy pathlowestCommonAncestor_236.cpp
File metadata and controls
58 lines (54 loc) · 1.52 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <stdio.h>
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *ans;
TreeNode *DFS(TreeNode *root, TreeNode *p, TreeNode *q) {
if (root == nullptr) {
return nullptr;
}
TreeNode* res = nullptr;
if (root == p || root == q) {
res = root;
}
TreeNode *left = DFS(root->left, p, q);
TreeNode *right = DFS(root->right, p, q);
if (left != nullptr && right != nullptr) {
if (ans == nullptr) ans = root;
}
if (res && (left || right)&& ans == nullptr) ans = root;
return left == nullptr ? right : left;
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (root == nullptr) {
return nullptr;
}
DFS(root, p, q);
return ans;
}
};
class Solution {
public:
TreeNode* ans;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr) return false;
bool lson = dfs(root->left, p, q);
bool rson = dfs(root->right, p, q);
if ((lson && rson) || ((root->val == p->val || root->val == q->val) && (lson || rson))) {
ans = root;
}
return lson || rson || (root->val == p->val || root->val == q->val);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ans;
}
};