337. 打家劫舍 III
https://leetcode-cn.com/problems/house-robber-iii/
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func rob(root *TreeNode) int { return Help(root) } //缓存很重要,可以存很多子问题的值 var m = map[*TreeNode]int{} func Help(root *TreeNode) int{ if root == nil{ return 0 } if v,ok := m[root];ok{ return v } res,do,not_do := 0,root.Val,0 //do / not_do if root.Right != nil{ do += Help(root.Right.Right) + Help(root.Right.Left) } if root.Left != nil{ do += Help(root.Left.Left) + Help(root.Left.Right) } not_do += Help(root.Left)+Help(root.Right) res = MAX(do,not_do) m[root] = res return res } func MAX(i,j int) int{ if i<j{ return j }else{ return i } }