Skip to content

Commit b9fddf6

Browse files
authored
Create 1373-maximum-sum-bst-in-binary-tree.js
1 parent 3ffa368 commit b9fddf6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
const maxSumBST = function (root) {
14+
let maxSum = 0
15+
postOrderTraverse(root)
16+
return maxSum
17+
18+
function postOrderTraverse(root) {
19+
if (root == null) return [Number.MAX_VALUE, -Infinity, 0] // {min, max, sum}, initialize min=MAX_VALUE, max=MIN_VALUE
20+
let left = postOrderTraverse(root.left)
21+
let right = postOrderTraverse(root.right)
22+
// The BST is the tree:
23+
if (
24+
!(
25+
left != null && // the left subtree must be BST
26+
right != null && // the right subtree must be BST
27+
root.val > left[1] && // the root's key must greater than maximum keys of the left subtree
28+
root.val < right[0]
29+
)
30+
)
31+
// the root's key must lower than minimum keys of the right subtree
32+
return null
33+
let sum = root.val + left[2] + right[2] // now it's a BST make `root` as root
34+
maxSum = Math.max(maxSum, sum)
35+
let min = Math.min(root.val, left[0])
36+
let max = Math.max(root.val, right[1])
37+
return [min, max, sum]
38+
}
39+
}

0 commit comments

Comments
 (0)