-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA_for_BT_BST.cpp
More file actions
97 lines (62 loc) · 1.98 KB
/
Copy pathLCA_for_BT_BST.cpp
File metadata and controls
97 lines (62 loc) · 1.98 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
86
87
88
89
90
91
92
93
94
95
96
97
#include <bits/stdc++.h>
using namespace std;
typedef struct Node{
int data;
Node* left;
Node* right;
}Node;
//Assumption keys are present in the tree
//Returns the LCA
Node* BST_lca(Node* root, int x, int y){
//TBD Base cases
if(root == NULL)
return NULL;
if(x < root->data && y < root->data) //Focus Left
return BST_lca(root->left, x, y);
if(x > root->data && y > root->data) //Focus Right
return BST_lca(root->right, x, y);
return root;
}
//Assumption keys are present in the tree
//Returns a node where any of the keys is found
Node* lca_keys_present(Node* root, int x, int y){
//TBD Base cases
if(root == NULL)
return NULL;
if(root->data == x || root->data == y) //Returns a node where any of the keys is found
return root;
Node* leftResult = lca_keys_present(root->left, x, y);
Node* rightResult = lca_keys_present(root->right, x, y);
if(leftResult && rightResult) //Both non null indicates we are on LCA i.e keys are on either side
return root;
return leftResult? leftResult : rightResult; //The non-null one contains the LCA
}
//Both keys may or may not be in the tree
typedef pair<Node*, int> result;
result lca(Node* root, int x, int y){
//TBD Base cases
if(root == NULL)
return {NULL, 0};
result leftResult = lca(root->left, x, y);
if(leftResult.first !=NULL) //LCA on left sub tree
return leftResult;
result rightResult = lca(root->right, x, y);
if(rightResult.first !=NULL) //LCA on right sub tree
return rightResult;
if(leftResult.second == 1 && rightResult.second == 1) //This is the LCA
return {root, 2};
if(root->data == x || root->data == y){
if(leftResult.second == 1 || rightResult.second == 1)
return{root, 2}; //This is the LCA (parent-childreln)
return {NULL, 1};
}
result q(NULL, 0);
return {NULL,0}; //TBD final check
}
int main() {
cout<<"Hello!"<<endl;
Node* a;
BST_lca(a, 10, 20);
lca(a, 10, 20);
return 0;
}