Returns LCA if node n1, n2 are present in the given binary tree, otherwise return -1
| 50 | // Returns LCA if node n1, n2 are present in the given binary tree, |
| 51 | // otherwise return -1 |
| 52 | int findLCA(Node *root, int n1, int n2) |
| 53 | { |
| 54 | // to store paths to n1 and n2 from the root |
| 55 | vector<int> path1, path2; |
| 56 | |
| 57 | // Find paths from root to n1 and root to n2. If either n1 or n2 |
| 58 | // is not present, return -1 |
| 59 | if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) |
| 60 | return -1; |
| 61 | |
| 62 | /* Compare the paths to get the first different value */ |
| 63 | int i; |
| 64 | for (i = 0; i < path1.size() && i < path2.size() ; i++) |
| 65 | if (path1[i] != path2[i]) |
| 66 | break; |
| 67 | return path1[i-1]; |
| 68 | } |
| 69 | |
| 70 | // Driver program to test above functions |
| 71 | int main() |