Lowest common ancestor in a binary Tree

Approach

  1. Define a recursive function rec that takes three parameters: root (the current node), p (first node to find the lowest common ancestor for), and q (second node to find the lowest common ancestor for).

  2. Check if the current node root is null or if it is either p or q. If any of these conditions is true, return the current node root as the lowest common ancestor.

  3. Recursively call the rec function for the left subtree of the current node and assign the result to a variable l.

  4. Recursively call the rec function for the right subtree of the current node and assign the result to a variable r.

  5. Check if both l and r are not null. If so, it means that p and q are found on different subtrees of the current node, and the current node root is their lowest common ancestor. Return the current node root.

  6. If l is null, it means that both p and q are on the right subtree (or not present in the tree). Return r.

  7. If none of the above conditions are met, it means that both p and q are on the left subtree (or not present in the tree). Return l.

  8. 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), and q (second node to find the lowest common ancestor for).

  9. Return the result of calling the rec function with the parameters root, p, and q. This will find and return the lowest common ancestor of nodes p and q in the given binary tree.

Comments

Popular posts from this blog

LeetCode 3Sum

30. Substring with Concatenation of All Words