This website uses cookies to enhance the user experience

Lowest Common Ancestor in Binary Tree

Difficulty: 🔥 Hard

Problem Statement

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example
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 = 5, q = 4
Output: 5
Constraints
  • The number of nodes in the tree is in the range [2, 10^5].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.

Expected Challenge Output

When the function lowestCommonAncestor is called with the given example inputs, the expected output is the value of the lowest common ancestor of the two nodes.

let root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
let p = root.left;  // 5
let q = root.right;  // 1
console.log(lowestCommonAncestor(root, p, q).val);  // Output: 3

p = root.left;  // 5
q = root.left.right.right;  // 4
console.log(lowestCommonAncestor(root, p, q).val);  // Output: 5
class TreeNode {
constructor(val=0, left=null, right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}

function lowestCommonAncestor(root, p, q) {
// YOUR SOLUTION HERE
}

Memory: 0

CPU: 0