|
| 1 | +/** |
| 2 | +
|
| 3 | +Given a binary tree, find the largest subtree |
| 4 | +which is a Binary Search Tree (BST), |
| 5 | +where largest means subtree with largest number of nodes in it. |
| 6 | +
|
| 7 | +Note: |
| 8 | +A subtree must include all of its descendants. |
| 9 | +
|
| 10 | +Example: |
| 11 | +
|
| 12 | +Input: [10,5,15,1,8,null,7] |
| 13 | +
|
| 14 | + 10 |
| 15 | + / \ |
| 16 | + 5 15 |
| 17 | + / \ \ |
| 18 | +1 8 7 |
| 19 | +
|
| 20 | +Output: 3 |
| 21 | +Explanation: The Largest BST Subtree in this case is the highlighted one. |
| 22 | + The return value is the subtree's size, which is 3. |
| 23 | +
|
| 24 | +*/ |
| 25 | + |
| 26 | +/** |
| 27 | + * Definition for a binary tree node. |
| 28 | + * function TreeNode(val) { |
| 29 | + * this.val = val; |
| 30 | + * this.left = this.right = null; |
| 31 | + * } |
| 32 | + */ |
| 33 | +/** |
| 34 | + * @param {TreeNode} root |
| 35 | + * @return {number} |
| 36 | + */ |
| 37 | +const largestBSTSubtree = function(root) { |
| 38 | + const res = helper(root) |
| 39 | + return res[2] |
| 40 | +} |
| 41 | + |
| 42 | +function helper(node) { |
| 43 | + if (!node) return [Number.MAX_VALUE, -Number.MAX_VALUE, 0] |
| 44 | + const left = helper(node.left) |
| 45 | + const right = helper(node.right) |
| 46 | + if (node.val > left[1] && node.val < right[0]) { |
| 47 | + return [ |
| 48 | + Math.min(node.val, left[0]), |
| 49 | + Math.max(node.val, right[1]), |
| 50 | + left[2] + right[2] + 1 |
| 51 | + ] |
| 52 | + } else { |
| 53 | + return [-Number.MAX_VALUE, Number.MAX_VALUE, Math.max(left[2], right[2])] |
| 54 | + } |
| 55 | +} |
0 commit comments