337.house-robber-iii.go 833 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. type node struct {
  10. root *TreeNode
  11. done bool
  12. }
  13. func rob(root *TreeNode) int {
  14. m := make(map[node]int)
  15. return maxInt(helper(root, false, &m), helper(root, true, &m))
  16. }
  17. func helper(root *TreeNode, done bool, m *map[node]int) int {
  18. if root == nil {
  19. return 0
  20. }
  21. if max, ok := (*m)[node{root, done}]; ok { // Memory search
  22. return max
  23. }
  24. var max int
  25. if done {
  26. max = helper(root.Left, false, m) + helper(root.Right, false, m)
  27. } else {
  28. max = maxInt(root.Val+helper(root.Left, true, m)+helper(root.Right, true, m), helper(root.Left, false, m)+helper(root.Right, false, m))
  29. }
  30. (*m)[node{root, done}] = max
  31. return max
  32. }
  33. func maxInt(x, y int) int {
  34. if x < y {
  35. return y
  36. }
  37. return x
  38. }