Overview
Given a binary tree and two nodes p and q, find their lowest common ancestor (LCA) — the deepest node that has both p and q as descendants (a node can be a descendant of itself).
Constraints
- The number of nodes is in the range
[2, 100,000]. - All node values are unique.
p !== qand both exist in the tree.
Examples
// Tree: [3,5,1,6,2,0,8,null,null,7,4] lowestCommonAncestor(root, 5, 1); // => 3 lowestCommonAncestor(root, 5, 4); // => 5
Solution
Reveal solution
function lowestCommonAncestor(root, p, q) {
if (!root || root.val === p || root.val === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left && right) return root;
return left || right;
}Resources
lowest-common-ancestor-binary-tree.js
Lowest Common Ancestor of a Binary Tree
mediumcodingAlgorithmsBinary Trees
Overview
Given a binary tree and two nodes p and q, find their lowest common ancestor (LCA) — the deepest node that has both p and q as descendants (a node can be a descendant of itself).
Constraints
- The number of nodes is in the range
[2, 100,000]. - All node values are unique.
p !== qand both exist in the tree.
Examples
// Tree: [3,5,1,6,2,0,8,null,null,7,4] lowestCommonAncestor(root, 5, 1); // => 3 lowestCommonAncestor(root, 5, 4); // => 5
Solution
Reveal solution
function lowestCommonAncestor(root, p, q) {
if (!root || root.val === p || root.val === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left && right) return root;
return left || right;
}Resources
NameTopicDifficulty
103 of 103 problems