Lowest Common Ancestor of a Binary Tree

Medium#236tree nodes

You get the root of a binary tree and two different nodes of it, p and q. Find their lowest common ancestor: the deepest node that has both p and q in its subtree; a node counts as part of its own subtree. Our tree: 5 with children 8 and 2; 8 has children 4 and 1; 1 has a left child 7; 2 has a right child 9. p = 4, q = 7 — the answer is 8.

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child; its values are all different. p and q: two nodes of that tree, which the tests name by their values.
returns
Their lowest common ancestor: the deepest node that has both p and q below it, a node counting as below itself. Return the node of root itself; the tests name it by its value, node 3.
constraints
  • 2 ≤ the number of nodes ≤ 1000
  • −10⁹ ≤ Node.val ≤ 10⁹
  • the values of the nodes are all different
  • p and q are in the tree
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
function lowestCommonAncestor(root, p, q) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.