|
| 1 | +/** |
| 2 | + * 1373. Maximum Sum BST in Binary Tree |
| 3 | + * https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a |
| 7 | + * Binary Search Tree (BST). |
| 8 | + * |
| 9 | + * Assume a BST is defined as follows: |
| 10 | + * - The left subtree of a node contains only nodes with keys less than the node's key. |
| 11 | + * - The right subtree of a node contains only nodes with keys greater than the node's key. |
| 12 | + * - Both the left and right subtrees must also be binary search trees. |
| 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 | + * @return {number} |
| 26 | + */ |
| 27 | +var maxSumBST = function(root) { |
| 28 | + let result = 0; |
| 29 | + traverse(root); |
| 30 | + return result; |
| 31 | + |
| 32 | + function traverse(node) { |
| 33 | + if (!node) return { isBST: true, min: Infinity, max: -Infinity, sum: 0 }; |
| 34 | + |
| 35 | + const left = traverse(node.left); |
| 36 | + const right = traverse(node.right); |
| 37 | + |
| 38 | + if (left.isBST && right.isBST && node.val > left.max && node.val < right.min) { |
| 39 | + const currentSum = node.val + left.sum + right.sum; |
| 40 | + result = Math.max(result, currentSum); |
| 41 | + return { |
| 42 | + isBST: true, |
| 43 | + min: Math.min(node.val, left.min), |
| 44 | + max: Math.max(node.val, right.max), |
| 45 | + sum: currentSum |
| 46 | + }; |
| 47 | + } |
| 48 | + |
| 49 | + return { isBST: false, min: 0, max: 0, sum: 0 }; |
| 50 | + } |
| 51 | +}; |
0 commit comments