Skip to main content

1123.js

/** ------------------------------------------------------------------------------
*
* 1123. Lowest Common Ancestor of Deepest Leaves
* Topics: Tree, DFS
* https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/?envType=daily-question&envId=2025-04-04
*
------------------------------------------------------------------------------ */
const maxDepth = (d = (n) => (n ? 1 + Math.max(d(n.left), d(n.right)) : 0))

/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var lcaDeepestLeaves = function (root) {
const [depthLeft, depthRight] = [maxDepth(root.left), maxDepth(root.right)]
if (depthLeft === depthRight) {
return root
}
return lcaDeepestLeaves(depthLeft > depthRight ? root.left : root.right)
}

console.log(lcaDeepestLeaves([3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]))