|
| 1 | +/** |
| 2 | + * 1080. Insufficient Nodes in Root to Leaf Paths |
| 3 | + * https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree and an integer limit, delete all insufficient nodes in the |
| 7 | + * tree simultaneously, and return the root of the resulting binary tree. |
| 8 | + * |
| 9 | + * A node is insufficient if every root to leaf path intersecting this node has a sum strictly |
| 10 | + * less than limit. |
| 11 | + * |
| 12 | + * A leaf is a node with no children. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Definition for a binary tree node. |
| 17 | + * function TreeNode(val, left, right) { |
| 18 | + * this.val = (val===undefined ? 0 : val) |
| 19 | + * this.left = (left===undefined ? null : left) |
| 20 | + * this.right = (right===undefined ? null : right) |
| 21 | + * } |
| 22 | + */ |
| 23 | +/** |
| 24 | + * @param {TreeNode} root |
| 25 | + * @param {number} limit |
| 26 | + * @return {TreeNode} |
| 27 | + */ |
| 28 | +var sufficientSubset = function(root, limit) { |
| 29 | + return checkPath(root, 0) ? root : null; |
| 30 | + |
| 31 | + function checkPath(node, sum) { |
| 32 | + if (!node) return false; |
| 33 | + if (!node.left && !node.right) return sum + node.val >= limit; |
| 34 | + |
| 35 | + const leftValid = checkPath(node.left, sum + node.val); |
| 36 | + const rightValid = checkPath(node.right, sum + node.val); |
| 37 | + |
| 38 | + if (!leftValid) node.left = null; |
| 39 | + if (!rightValid) node.right = null; |
| 40 | + |
| 41 | + return leftValid || rightValid; |
| 42 | + } |
| 43 | +}; |
0 commit comments