124.go 891 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package main
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func maxPathSum(root *TreeNode) int {
  11. maxInt := func(x, y int) int {
  12. if x > y {
  13. return x
  14. }
  15. return y
  16. }
  17. var recurse func(*TreeNode) int
  18. max := root.Val
  19. recurse = func(root *TreeNode) int { // Sum every path bottom-up is the key
  20. if root == nil {
  21. return 0
  22. }
  23. maxL := maxInt(0, recurse(root.Left)) // 0 means do not pick the path
  24. maxR := maxInt(0, recurse(root.Right))
  25. max = maxInt(max, root.Val+maxL+maxR)
  26. return root.Val + maxInt(maxL, maxR)
  27. }
  28. recurse(root)
  29. return max
  30. }
  31. // func main() {
  32. // tree := toBinaryTree(newInt(-10), newInt(9), newInt(20), nil, nil, newInt(15), newInt(7))
  33. // println(maxPathSum(tree), 42)
  34. // tree = toBinaryTree(newInt(1), newInt(2), newInt(3))
  35. // println(maxPathSum(tree), 6)
  36. // }