Lowest Common Ancestor (LCA) of binary tree in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to find lowest common ancestor(LCA) of two nodes in binary tree. Lets understand with example.

As you can see here, LCA is nothing but lowest common parent of two nodes.

Recursive Algorithm (For nodes A and B):

  • If node is null, return it
  • If we find A or B, return it.
  • Traverse left subtree and right subtree
  •  If we get both left and right for any node as not null, it will be lowest common ancestor of two given nodes

Complete java program:

When you run above program, you will get below output:

Java Binary tree tutorial:

Please go through java interview programs for more such programs.

Add Comment