⬅ Previous Topic
Check if All Leaf Nodes are at the Same Level in a Binary TreeNext Topic ⮕
Solve the Tree Isomorphism Problem⬅ Previous Topic
Check if All Leaf Nodes are at the Same Level in a Binary TreeNext Topic ⮕
Solve the Tree Isomorphism Problemroot
is null
or equal to p
or q
, return root
.left = lowestCommonAncestor(root.left, p, q)
.right = lowestCommonAncestor(root.right, p, q)
.left
and right
are non-null, then root
is the LCA; return root
.left
or right
is non-null, return the non-null value.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 3
# / \
# 5 1
# / \ / \
# 6 2 0 8
# / \
# 7 4
root = TreeNode(3)
root.left = TreeNode(5)
root.right = TreeNode(1)
root.left.left = TreeNode(6)
root.left.right = TreeNode(2)
root.right.left = TreeNode(0)
root.right.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(4)
sol = Solution()
# Assume we want to find LCA of nodes 7 and 4
lca = sol.lowestCommonAncestor(root, root.left.right.left, root.left.right.right)
print('LCA:', lca.val if lca else 'None')
⬅ Previous Topic
Check if All Leaf Nodes are at the Same Level in a Binary TreeNext Topic ⮕
Solve the Tree Isomorphism ProblemYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.