class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function lowestCommonAncestor(root, p, q) {
if (root === null) return null;
if (root === p || root === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left !== null && right !== null) return root;
return left !== null ? left : right;
}
// Build tree
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
const p = root.left.left; // Node 4
const q = root.left.right; // Node 5
const lca = lowestCommonAncestor(root, p, q);
console.log(lca.val);if (root === null) return null;
stop if reached empty subtree
if (root === p || root === q) return root;
return current node if it matches one of the targets
const left = lowestCommonAncestor(root.left, p, q);
search left subtree for targets
const right = lowestCommonAncestor(root.right, p, q);
search right subtree for targets
if (left !== null && right !== null) return root;
if targets found in both subtrees, current node is LCA
return left !== null ? left : right;
otherwise return non-null subtree result