/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxSumBST(root *TreeNode) (ans int) {
const inf = 1 << 30
var dfs func(root *TreeNode) [4]int
dfs = func(root *TreeNode) [4]int {
if root == nil {
return [4]int{1, inf, -inf, 0}
}
l, r := dfs(root.Left), dfs(root.Right)
if l[0] == 1 && r[0] == 1 && l[2] < root.Val && root.Val < r[1] {
s := l[3] + r[3] + root.Val
ans = max(ans, s)
return [4]int{1, min(l[1], root.Val), max(r[2], root.Val), s}
}
return [4]int{}
}
dfs(root)
return
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxSumBST(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> tuple:
if root is None:
return 1, inf, -inf, 0
lbst, lmi, lmx, ls = dfs(root.left)
rbst, rmi, rmx, rs = dfs(root.right)
if lbst and rbst and lmx < root.val < rmi:
nonlocal ans
s = ls + rs + root.val
ans = max(ans, s)
return 1, min(lmi, root.val), max(rmx, root.val), s
return 0, 0, 0, 0
ans = 0
dfs(root)
return ans
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
const INF = 0x3f3f3f3f
type SubTree struct {
IsBST bool
MinVal int
MaxVal int
SumVal int
}
var res int
func maxSumBST(root *TreeNode) int {
res = 0
dfs(root)
return res
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}
func dfs(root *TreeNode) *SubTree {
if root == nil {
return &SubTree{true, INF, -INF, 0}
}
left := dfs(root.Left)
right := dfs(root.Right)
if left.IsBST && right.IsBST && root.Val > left.MaxVal && root.Val < right.MinVal {
sum := root.Val + left.SumVal + right.SumVal
res = max(res, sum)
return &SubTree{true, min(left.MinVal, root.Val), max(root.Val, right.MaxVal), sum}
} else {
return &SubTree{false, 0, 0, 0}
}
}