Lowest Common Ancestor of a Binary Tree
Medium Trees
root is the root of a binary tree whose nodes all hold different values. p and q are two of its nodes, or the same node twice; the examples name each node by the value it holds.
A node's subtree is the node itself and every node below it: its children, their children, and so on down. A node is a common ancestor of p and q when both are in its subtree, so the root is always one.
Return the lowest common ancestor of p and q: of all their common ancestors, the one deepest in the tree, farthest from the root. When q is in the subtree of p, that is p itself.
Example 1
1 is in the subtree of 12, through its left child 5, and 7 is the right child of 12, so 12 holds both. The root, 8, holds them too, but 12 is deeper.
Example 2
10 is a child of 5, and 5 is in its own subtree, so 5 itself is the deepest node that holds both.
Example 3
Constraints
1 ≤ number of nodes ≤ 10⁵-10⁹ ≤ node.val ≤ 10⁹, and no two nodes hold the same valuepandqare nodes of the tree, and may be the same node
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
See the AI roundMore Trees
- Validate Binary Search TreeAI round · Medium
- Binary Tree Level Order TraversalAI round · Medium
- Symmetric TreeAI round · Easy
- Binary Tree Vertical Order TraversalMedium
- Find Leaves of Binary TreeMedium