Lowest Common Ancestor of a Binary Tree
Explore how to determine the lowest common ancestor of two nodes in a binary tree. This lesson helps you understand the problem constraints, definition, and approach using depth-first search strategies. By mastering this, you will improve your ability to solve binary tree problems efficiently in coding interviews.
We'll cover the following...
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,
pandq, is defined as the lowest node in the binary tree that has bothpandqas descendants.A node can also be a descendant of itself. For example, if
qis a descendant ofp, and we know thatpis a descendant of itself, thenpwill be the lowest common ancestor ofpandq.
Constraints:
- All
Node.dataare unique. pqpandqexist 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 of a binary tree node// type TreeNode[T any] struct {// Data T// Left *TreeNode[T]// Right *TreeNode[T]// }package mainimport (. "golang-test-code/ds_v1/BinaryTree") // TreeNode[T]type Solution struct {lca *TreeNode[int]}func (s *Solution) lowestCommonAncestor(root, p, q *TreeNode[int]) *TreeNode[int] {// Replace this placeholder return statement with your codereturn nil}