|
| 1 | +/** |
| 2 | + * 333. Largest BST Subtree |
| 3 | + * https://leetcode.com/problems/largest-bst-subtree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, find the largest subtree, which is also a Binary Search |
| 7 | + * Tree (BST), where the largest means subtree has the largest number of nodes. |
| 8 | + * |
| 9 | + * A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned |
| 10 | + * properties: |
| 11 | + * - The left subtree values are less than the value of their parent (root) node's value. |
| 12 | + * - The right subtree values are greater than the value of their parent (root) node's value. |
| 13 | + * |
| 14 | + * Note: A subtree must include all of its descendants. |
| 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 {number} |
| 28 | + */ |
| 29 | +var largestBSTSubtree = function(root) { |
| 30 | + let maxSize = 0; |
| 31 | + traverse(root); |
| 32 | + return maxSize; |
| 33 | + |
| 34 | + function traverse(node) { |
| 35 | + if (!node) return { isBST: true, size: 0, min: Infinity, max: -Infinity }; |
| 36 | + |
| 37 | + const left = traverse(node.left); |
| 38 | + const right = traverse(node.right); |
| 39 | + if (left.isBST && right.isBST && node.val > left.max && node.val < right.min) { |
| 40 | + const size = left.size + right.size + 1; |
| 41 | + maxSize = Math.max(maxSize, size); |
| 42 | + return { |
| 43 | + isBST: true, |
| 44 | + size, |
| 45 | + min: Math.min(left.min, node.val), |
| 46 | + max: Math.max(right.max, node.val) |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + return { isBST: false, size: 0, min: 0, max: 0 }; |
| 51 | + } |
| 52 | +}; |
0 commit comments