-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy path236.lowest-common-ancestor-of-a-binary-tree.cpp
More file actions
70 lines (50 loc) · 1.23 KB
/
236.lowest-common-ancestor-of-a-binary-tree.cpp
File metadata and controls
70 lines (50 loc) · 1.23 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
// 112. Path Sum
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
public:
Node(int data) {
this->data = data;
left = NULL;
right = NULL;
}
};
Node* buildTree() {
int n;
cin >> n;
if(n == -1) {
return NULL;
}
Node* root = new Node(n);
root->left = buildTree();
root->right = buildTree();
return root;
}
Node* lowestCommonAncestor(Node* root, Node* p, Node* q) {
if(root == NULL)
return root;
if(root == p || root == q)
return root;
else {
Node* leftAns = lowestCommonAncestor(root->left, p, q);
Node* rightAns = lowestCommonAncestor(root->right, p, q);
if(leftAns != NULL && rightAns != NULL)
return root;
else if(leftAns == NULL)
return rightAns;
else
return leftAns;
}
}
int main() {
Node* root = buildTree();
Node* p = new Node(5);
Node* q = new Node(1);
Node* ans = lowestCommonAncestor(root, p, q);
cout << ans->data << endl;
return 0;
}