|
| 1 | +/** |
| 2 | + * 1123. Lowest Common Ancestor of Deepest Leaves |
| 3 | + * https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. |
| 7 | + * |
| 8 | + * Recall that: |
| 9 | + * - The node of a binary tree is a leaf if and only if it has no children |
| 10 | + * - The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of |
| 11 | + * its children is d + 1. |
| 12 | + * - The lowest common ancestor of a set S of nodes, is the node A with the largest depth such |
| 13 | + * that every node in S is in the subtree with root A. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * Definition for a binary tree node. |
| 18 | + * function TreeNode(val, left, right) { |
| 19 | + * this.val = (val===undefined ? 0 : val) |
| 20 | + * this.left = (left===undefined ? null : left) |
| 21 | + * this.right = (right===undefined ? null : right) |
| 22 | + * } |
| 23 | + */ |
| 24 | +/** |
| 25 | + * @param {TreeNode} root |
| 26 | + * @return {TreeNode} |
| 27 | + */ |
| 28 | +var lcaDeepestLeaves = function(root) { |
| 29 | + return findDepthAndNode(root).node; |
| 30 | + |
| 31 | + function findDepthAndNode(node) { |
| 32 | + if (!node) return { depth: 0, node: null }; |
| 33 | + |
| 34 | + const left = findDepthAndNode(node.left); |
| 35 | + const right = findDepthAndNode(node.right); |
| 36 | + |
| 37 | + if (left.depth === right.depth) { |
| 38 | + return { depth: left.depth + 1, node: node }; |
| 39 | + } |
| 40 | + |
| 41 | + const deeper = left.depth > right.depth ? left : right; |
| 42 | + return { depth: deeper.depth + 1, node: deeper.node }; |
| 43 | + } |
| 44 | +}; |
0 commit comments