236. Lowest Common Ancestor of a Binary Tree
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the Lowest Common Ancestor (LCA) of two given nodes, p and q, in a binary tree. The LCA is defined as the deepest node that has both p and q as its descendants. A key detail is that a node is considered a descendant of itself. The problem guarantees that both p and q exist in the tree, are distinct, and the tree node values are unique.
Solution
Lowest Common Ancestor of a Binary Tree in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# Base case: if the root is None, or if we found p or q, return the root.
# If we find p or q, we return it. The parent node will decide if this is the LCA.
# If the other node is in a different subtree of the parent, the parent is the LCA.
# If the other node is in the same subtree, this returned node is the LCA (since a node can be a descendant of itself).
if not root or root == p or root == q:
return root
# Recursively search in the left and right subtrees.
left_lca = self.lowestCommonAncestor(root.left, p, q)
right_lca = self.lowestCommonAncestor(root.right, p, q)
# If both left_lca and right_lca are non-None, it means p and q were found
# in different subtrees of the current root. Thus, the current root is their LCA.
if left_lca and right_lca:
return root
# Otherwise, the LCA must be in either the left or the right subtree.
# If one of them is None, the other one is the LCA (it could be p, q, or a node higher up).
# This also handles the case where both are None, returning None.
return left_lca or right_lca
Lowest Common Ancestor of a Binary Tree in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Base case: if the root is null, or if we found p or q, return the root.
// If we find p or q, we return it. The parent node will decide if this is the LCA.
// If the other node is in a different subtree of the parent, the parent is the LCA.
// If the other node is in the same subtree, this returned node is the LCA (since a node can be a descendant of itself).
if (root == null || root == p || root == q) {
return root;
}
// Recursively search in the left and right subtrees.
TreeNode leftLCA = lowestCommonAncestor(root.left, p, q);
TreeNode rightLCA = lowestCommonAncestor(root.right, p, q);
// If both leftLCA and rightLCA are non-null, it means p and q were found
// in different subtrees of the current root. Thus, the current root is their LCA.
if (leftLCA != null && rightLCA != null) {
return root;
}
// Otherwise, the LCA must be in either the left or the right subtree.
// If one of them is null, the other one is the LCA (it could be p, q, or a node higher up).
// If both are null, this function will return null, indicating p and q are not in this subtree.
return leftLCA != null ? leftLCA : rightLCA;
}
}
Lowest Common Ancestor of a Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// Base case: if the root is null, or if we found p or q, return the root.
// If we find p or q, we return it. The parent node will decide if this is the LCA.
// If the other node is in a different subtree of the parent, the parent is the LCA.
// If the other node is in the same subtree, this returned node is the LCA (since a node can be a descendant of itself).
if (root == nullptr || root == p || root == q) {
return root;
}
// Recursively search in the left and right subtrees.
TreeNode* leftLCA = lowestCommonAncestor(root->left, p, q);
TreeNode* rightLCA = lowestCommonAncestor(root->right, p, q);
// If both leftLCA and rightLCA are non-null, it means p and q were found
// in different subtrees of the current root. Thus, the current root is their LCA.
if (leftLCA != nullptr && rightLCA != nullptr) {
return root;
}
// Otherwise, the LCA must be in either the left or the right subtree.
// If one of them is null, the other one is the LCA (it could be p, q, or a node higher up).
// If both are null, this function will return null, indicating p and q are not in this subtree.
return leftLCA != nullptr ? leftLCA : rightLCA;
}
};
Lowest Common Ancestor of a Binary Tree in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
// Base case: if the root is null, or if we found p or q, return the root.
// If we find p or q, we return it. The parent node will decide if this is the LCA.
// If the other node is in a different subtree of the parent, the parent is the LCA.
// If the other node is in the same subtree, this returned node is the LCA (since a node can be a descendant of itself).
if (root === null || root === p || root === q) {
return root;
}
// Recursively search in the left and right subtrees.
const leftLCA = lowestCommonAncestor(root.left, p, q);
const rightLCA = lowestCommonAncestor(root.right, p, q);
// If both leftLCA and rightLCA are non-null, it means p and q were found
// in different subtrees of the current root. Thus, the current root is their LCA.
if (leftLCA !== null && rightLCA !== null) {
return root;
}
// Otherwise, the LCA must be in either the left or the right subtree.
// If one of them is null, the other one is the LCA (it could be p, q, or a node higher up).
// If both are null, this function will return null, indicating p and q are not in this subtree.
return leftLCA !== null ? leftLCA : rightLCA;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.