1
var maxSumBST = function (root) {3
const dfs = (node) => {5
if (!node) return [true, 0, Infinity, -Infinity];8
if (node && !node.left && !node.right) {9
max = Math.max(max, node.val);10
return [true, node.val, node.val, node.val];13
const [isLeftValid, leftVal, leftMin, leftMax] = dfs(node.left);14
const [isRightValid, rightVal, rightMin, rightMax] = dfs(node.right);17
* To establish that the current node is also a valid BST, we need to verify the following:18
* 1. Left sub tree is a valid BST19
* 2. Right sub tree is a valid BST20
* 3. The values in the left BST are smaller than current node's value21
* 4. The values in the right BST are greater than current node's value29
max = Math.max(max, leftVal + rightVal + node.val);32
leftVal + rightVal + node.val,43
* [Infinity and -Infinity are to depict NoNode cases]45
Math.min(node.val, leftMin),46
Math.max(node.val, rightMax),50
return [false, 0, leftMax, rightMin];