Lowest common ancestor in a binary Tree
Approach
-
Define a recursive function
rec
that 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
root
is null or if it is eitherp
orq
. If any of these conditions is true, return the current noderoot
as the lowest common ancestor. -
Recursively call the
rec
function for the left subtree of the current node and assign the result to a variablel
. -
Recursively call the
rec
function for the right subtree of the current node and assign the result to a variabler
. -
Check if both
l
andr
are not null. If so, it means thatp
andq
are found on different subtrees of the current node, and the current noderoot
is their lowest common ancestor. Return the current noderoot
. -
If
l
is null, it means that bothp
andq
are on the right subtree (or not present in the tree). Returnr
. -
If none of the above conditions are met, it means that both
p
andq
are on the left subtree (or not present in the tree). Returnl
. -
Define a function
lowestCommonAncestor
that 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
rec
function with the parametersroot
,p
, andq
. This will find and return the lowest common ancestor of nodesp
andq
in the given binary tree.
Comments
Post a Comment