MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / findLCA

Function findLCA

CPP/graph_tree/LCA_Binary-tree.cpp:52–68  ·  view source on GitHub ↗

Returns LCA if node n1, n2 are present in the given binary tree, otherwise return -1

Source from the content-addressed store, hash-verified

50// Returns LCA if node n1, n2 are present in the given binary tree,
51// otherwise return -1
52int 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
71int main()

Callers 1

mainFunction · 0.85

Calls 2

findPathFunction · 0.85
sizeMethod · 0.45

Tested by

no test coverage detected