Lowest Common Ancestor

Problem

Intution

Whenever we are given two nodes and asked to find the LCA, we recursively explore the left and right subtrees

When we reach leaf node or a node which is null, we will return null

But if we find a node or a value, we are looking for, we return that node. So whatever treenodes that are in the stack will be returning themselves

We just traverse left and right subtree recursively

At the end there are three cases:

  1. Left Subtree is null -> Then return right subtree

  2. Right Substree is null -> Then return left subtree

  3. If both are not null -> Return the root itself

Code

Last updated