Lowest Common Ancestor in a Binary Tree
Try to solve the Lowest Common Ancestor of a Binary Tree problem.
Statement
Given the root node of a binary tree with nodes, your task is to find the lowest common ancestor of two of its nodes, p
and q
.
Note: The lowest common ancestor of two nodes,
p
andq
, is defined as the lowest node in the binary tree that has bothp
andq
as descendants.A node can also be a descendant of itself. For example, if
q
is a descendant ofp
, and we know thatp
is a descendant of itself, thenp
will be the lowest common ancestor ofp
andq
.
Constraints:
- All
Node.data
are unique. p
q
p
andq
exist in the tree.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Lowest Common Ancestor in a Binary Tree
What is the lowest common ancestor of and in the following binary tree?
5
/ \
6 7
/ \
8 9
5
6
7
8
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
# Definition for a binary tree node# class TreeNode:# def __init__(self, data):# self.data = data# self.left = None# self.right = Nonefrom ds_v1.BinaryTree.BinaryTree import TreeNodeclass Solution:def lowest_common_ancestor(self, current_node, p, q):# Replace this placeholder return statement with your codereturn None