BackmediumTrees trees medium

Binary Tree Common Ancestor Node Solution

Problem Statement

Given a binary tree and two distinct node values, find the lowest common ancestor node of the two values. The lowest common ancestor is the node farthest from the root that has both values in its subtree. If one value does not exist in the tree, return null.

Example 1
Input
[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]
Output
3

Explanation: The lowest common ancestor of 5 and 1 is 3, as it is the farthest node from the root that has both values in its subtree.

Constraints

  • The binary tree has at most 10^4 nodes.
  • Each node value is unique and within the range [0, 10^5].
  • The two given node values are distinct.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free