-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLCA-of-Binary-Tree.cpp
69 lines (58 loc) · 1.63 KB
/
LCA-of-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
66
67
68
69
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class TreeNode {
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
};
// Helper function to find path from root to a destination node
bool getPath(TreeNode<int> *root, vector<int> &path, int dest) {
// If the root is NULL, return false
if(!root) {
return false;
}
// Push the root's data into the path vector
path.push_back(root->data);
// If the root's data is equal to the destination, return true
if(root->data == dest) {
return true;
}
// Recursively find the path from the root's left and right subtrees
if(getPath(root->left, path, dest)) {
return true;
}
if(getPath(root->right, path, dest)) {
return true;
}
// If the destination is not found, pop the root's data from the path vector
path.pop_back();
return false;
}
int lowestCommonAncestor(TreeNode<int> *root, int x, int y)
{
// Find the paths from the root to the nodes with data x and y
vector<int> pathx, pathy;
getPath(root, pathx, x);
getPath(root, pathy, y);
// Calculate the lengths of the paths
int lenx = pathx.size(), leny = pathy.size();
int res = -1;
// Compare the paths
for(int i=0; i<min(lenx, leny); i++) {
// If the nodes are not equal, return the last common node
if(pathx[i] != pathy[i]) {
return res;
}
// Update the last common node
res = pathx[i];
}
// Return the last common node
return res;
}