# Lowest Common Ancestor of a Binary Tree in Python

Suppose we have a binary tree. we have to find the Lowest common ancestor nodes of two given nodes. The LCA of two nodes p and q is actually as the lowest node in tree that has both p and q as decedent. So if the binary tree is like [3,5,1,6,2,0,8,null,null,7,4]. The tree will be like −

Here LCA of 5 and 1 is 3

To solve this, we will follow these steps −

• If the tree is empty, then return null

• if p and q both are same as root, then return root

• left := LCA of left subtree of the root using p and q

• right := LCA of right subtree of the root using p and q

• if left and right both are non-zero, then return root

• return left OR right

Let us see the following implementation to get better understanding −

## Example

class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root:
return None
if root == p or root==q:class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root:
return None
if root == p or root==q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if right and left:
return root
return right or left

## Input

[3,5,1,6,2,0,8,null,null,7,4]
5
1

## Output

3
Published on 05-Feb-2020 10:18:42