-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathlowest-common-ancestor-of-a-binary-tree.cpp
65 lines (56 loc) · 1.66 KB
/
lowest-common-ancestor-of-a-binary-tree.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
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Solution 1
class Solution {
public:
TreeNode* findLCA(TreeNode* node, TreeNode* p, TreeNode* q, bool& foundP, bool& foundQ) {
if (node == NULL) {
return NULL;
}
TreeNode* res = NULL;
bool enterFoundP = foundP;
bool enterFoundQ = foundQ;
// find children first
if (node->left) {
res = findLCA(node->left, p, q, foundP, foundQ);
if (res) {
return res;
}
}
if (node->right) {
res = findLCA(node->right, p, q, foundP, foundQ);
if (res) {
return res;
}
}
if (node == p) {
foundP = true;
}
if (node == q) {
foundQ = true;
}
if (foundP && foundQ && !enterFoundP && !enterFoundQ) {
return node;
}
return NULL;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
bool foundP = false;
bool foundQ = false;
return findLCA(root, p, q, foundP, foundQ);
}
};
// Solution 2: https://discuss.leetcode.com/topic/18561/4-lines-c-java-python-ruby
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
return !left ? right : !right ? left : root;
}