-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA(2).cpp
48 lines (39 loc) · 1.04 KB
/
LCA(2).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
#include <vector>
using namespace std;
/**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
/*
* Lowest Common Ancestor (2) : Divide and Conquer
*/
class Solution {
public:
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*/
ParentTreeNode *lowestCommonAncestorII(ParentTreeNode *root,
ParentTreeNode *A,
ParentTreeNode *B){
if(root == NULL) return NULL;
if(root == A || root == B) return root;
// divide
ParentTreeNode *left = lowestCommonAncestorII(root->left, A, B);
ParentTreeNode *right = lowestCommonAncestorII(root->right, A, B);
//conquer:
if(left != NULL && right != NULL) return root;
if(left != NULL) return left;
if(right != NULL) return right;
return NULL;
}
};
int main(){
// do sth interesting !
return 0;
}