Lowest common ancestor in a binary Tree
Approach
-
Define a recursive function
recthat takes three parameters:root(the current node),p(first node to find the lowest common ancestor for), andq(second node to find the lowest common ancestor for). -
Check if the current node
rootis null or if it is eitherporq. If any of these conditions is true, return the current noderootas the lowest common ancestor. -
Recursively call the
recfunction for the left subtree of the current node and assign the result to a variablel. -
Recursively call the
recfunction for the right subtree of the current node and assign the result to a variabler. -
Check if both
landrare not null. If so, it means thatpandqare found on different subtrees of the current node, and the current noderootis their lowest common ancestor. Return the current noderoot. -
If
lis null, it means that bothpandqare on the right subtree (or not present in the tree). Returnr. -
If none of the above conditions are met, it means that both
pandqare on the left subtree (or not present in the tree). Returnl. -
Define a function
lowestCommonAncestorthat takes three parameters:root(the root node of the tree),p(first node to find the lowest common ancestor for), andq(second node to find the lowest common ancestor for). -
Return the result of calling the
recfunction with the parametersroot,p, andq. This will find and return the lowest common ancestor of nodespandqin the given binary tree.
Comments
Post a Comment