|
| 1 | +/** |
| 2 | + * 865. Smallest Subtree with all the Deepest Nodes |
| 3 | + * https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, the depth of each node is the shortest distance to the root. |
| 7 | + * |
| 8 | + * Return the smallest subtree such that it contains all the deepest nodes in the original tree. |
| 9 | + * |
| 10 | + * A node is called the deepest if it has the largest depth possible among any node in the entire |
| 11 | + * tree. |
| 12 | + * |
| 13 | + * The subtree of a node is a tree consisting of that node, plus the set of all descendants of |
| 14 | + * that node. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * Definition for a binary tree node. |
| 19 | + * function TreeNode(val, left, right) { |
| 20 | + * this.val = (val===undefined ? 0 : val) |
| 21 | + * this.left = (left===undefined ? null : left) |
| 22 | + * this.right = (right===undefined ? null : right) |
| 23 | + * } |
| 24 | + */ |
| 25 | +/** |
| 26 | + * @param {TreeNode} root |
| 27 | + * @return {TreeNode} |
| 28 | + */ |
| 29 | +var subtreeWithAllDeepest = function(root) { |
| 30 | + return findDepthAndNode(root).node; |
| 31 | + |
| 32 | + function findDepthAndNode(node) { |
| 33 | + if (!node) return { depth: 0, node: null }; |
| 34 | + |
| 35 | + const left = findDepthAndNode(node.left); |
| 36 | + const right = findDepthAndNode(node.right); |
| 37 | + |
| 38 | + if (left.depth === right.depth) { |
| 39 | + return { depth: left.depth + 1, node: node }; |
| 40 | + } |
| 41 | + const deeper = left.depth > right.depth ? left : right; |
| 42 | + return { depth: deeper.depth + 1, node: deeper.node }; |
| 43 | + } |
| 44 | +}; |
0 commit comments