-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_04.08_lowestCommonAncestor.cc
More file actions
85 lines (78 loc) · 1.49 KB
/
Copy pathProblem_04.08_lowestCommonAncestor.cc
File metadata and controls
85 lines (78 loc) · 1.49 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
class Info
{
public:
bool findA;
bool findB;
TreeNode* ans;
Info(bool fa, bool fb, TreeNode* t)
{
this->findA = fa;
this->findB = fb;
this->ans = t;
}
};
public:
Info f(TreeNode* cur, TreeNode* p, TreeNode* q)
{
if (cur == NULL)
{
return Info(false, false, NULL);
}
Info left = f(cur->left, p, q);
Info right = f(cur->right, p, q);
bool findA = cur->val == p->val || left.findA || right.findA;
bool findB = cur->val == q->val || left.findB || right.findB;
TreeNode* ans = NULL;
if (left.ans != NULL)
{
ans = left.ans;
}
else if (right.ans != NULL)
{
ans = right.ans;
}
else
{
if (findA && findB)
{
ans = cur;
}
}
return Info(findA, findB, ans);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
return f(root, p, q).ans;
}
// 简化版
TreeNode* dfs(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (root == nullptr)
{
return nullptr;
}
if (root == p || root == q)
{
return root;
}
TreeNode* left = dfs(root->left, p, q);
TreeNode* right = dfs(root->right, p, q);
if (left && right)
{
return root;
}
return left == nullptr ? right : left;
}
};