Lowest Common Ancestor of Binary Tree Problem
Lowest Common Ancestor of Binary Tree Problem — ExecCode Medium DSA Practice
Solve the Lowest Common Ancestor of Binary Tree problem on ExecCode. Free online medium DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.
Problem description
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. The lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants (where we allow a node to be a descendant of itself).
Examples
Input root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 6, q = 4; Output 5. Input root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1; Output 3. Input root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 7, q = 4; Output 2
Constraints
The number of nodes in the tree is in the range [2, 10^5]. All Node.val are unique. p != q p and q will exist in the tree.
Practice Lowest Common Ancestor of Binary Tree free on ExecCode. Browse DSA problems, topic map, and placement guides.