Lowest Common Ancestor of a Binary Tree

What does the binary tree's lowest common ancestor represent?

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we are looking for the LCA. As a result, the common ancestor of nodes n1 and n2 that is placed the furthest from the root is the LCA of a binary tree containing nodes n1 and n2.

LCA (Lowest Common Ancestor) application:

The gap between pairs of nodes in a tree can be computed as the distance from the root to n1 plus the distance from the root to n2 minus twice the distance from the root to their lowest common ancestor.

Example:

Lowest Common Ancestor of a Binary Tree

Approach-

  • We know that because this is a Binary Search Tree, the left node will be less than or equal to the root node and the right node will be higher than the root node. In essence, this entails investigating the edge instances below:
  • Return null if the root is empty.
  • The LCA is the root node if one of the nodes is the root node (Lowest Common Ancestor)
  • The Root is the LCA if one node is greater than the root and another is less than the root.
  • There is no LCA if the two provided nodes are identical. deliver null.
  • Call the LCA function iteratively to compute steps 1 through 4 on the left node of the root if both nodes are smaller than the root.
  • Call the LCA function iteratively to compute steps 1 through 4 on the right node of the root if both nodes are greater than the root.

Program in C++:

Recursive Approach Using single Traversal

Time complexity:

O(n)

Space complexity:

O(n)

Function to print LCA:

Input:

Output:

3

Iterative Approach

Using Double Traversal and finding path for node p and q respectively than comparing their path to find LCA.

Complexity

Time complexity:

O(n)+O(n)

Space complexity:

O(n)+O(n)

Function to print LCA:

Input:

Output:

3

Function to print LCA in Python:

Input:

Output:

3

Function to print LCA in Java:

Input:

Output:

3





Latest Courses