This post is completed by 2 users

  • 0
Add to List
Hard

74. Lowest Common Ancestor in a Binary Tree (Not Binary Search Tree).

Objective: - Find the Lowest Common Ancestor of two given nodes in a Binary Tree

What is Lowest Common Ancestor

In a given binary tree, The lowest common ancestor of two nodes n1 and n2 will be a node X such that node X will be the lowest node who has n1 and n2 as its descendants.

Similar Problem: Lowest Common Ancestor in a Binary Search Tree.

Example:

Lowest Common Ancestor Example

Input: A binary Tree and two nodes n1 and n2.

Appraoch:

  1. Start will the root.
  2. If root matches with any of the given nodes (n1, n2) then return root as LCA.
  3. IF not then make recursive callas to left subtree and right subtree for the search of the nodes n1 and n2.
  4. Now both the nodes (n1 and n2) will be in the left subtree of the current visiting node OR it will be in the right subtree of current visiting OR n1 and n2 will be in each side of current visiting node.
  5. If you find a node which has one node in its left subtree and one node in its right subtree than this node will be our lowest common ancestor.
  6. If both the nodes (n1 and n2) will be in the left subtree of the current visiting node then go left
  7. If both the nodes (n1 and n2) will be in the right subtree of the current visiting node then go right.
  8. See Picture for better explanation
LCA in Binary Tree

Output:

Lowest Common Ancestor (8, 30 ) is 2
Lowest Common Ancestor (30, 5 ) is 5