Lowest Common Ancestor (LCA) of binary tree in java

Previous
Next

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

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

Java Binary tree tutorial:

Please go through java interview programs for more such programs.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog