Problem
Ask
Submissions

Problem: Lowest Common Ancestor of a Binary Tree

Medium
30 min
Explore how to identify the lowest common ancestor of two nodes in a binary tree by applying depth-first search techniques. Understand the definition and constraints, and practice solving this common tree problem with coding exercises designed to improve your interview skills.

Statement

Given the root node of a binary tree with nn 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 and q, is defined as the lowest node in the binary tree that has both p and q as descendants.

A node can also be a descendant of itself. For example, if q is a descendant of p, and we know that p is a descendant of itself, then p will be the lowest common ancestor of p and q.

Constraints:

  • 2n5002 \leq n \leq 500
  • All Node.data are unique.
  • p !=!= q
  • p and q exist in the tree.
Problem
Ask
Submissions

Problem: Lowest Common Ancestor of a Binary Tree

Medium
30 min
Explore how to identify the lowest common ancestor of two nodes in a binary tree by applying depth-first search techniques. Understand the definition and constraints, and practice solving this common tree problem with coding exercises designed to improve your interview skills.

Statement

Given the root node of a binary tree with nn 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 and q, is defined as the lowest node in the binary tree that has both p and q as descendants.

A node can also be a descendant of itself. For example, if q is a descendant of p, and we know that p is a descendant of itself, then p will be the lowest common ancestor of p and q.

Constraints:

  • 2n5002 \leq n \leq 500
  • All Node.data are unique.
  • p !=!= q
  • p and q exist in the tree.