Update 0337.打家劫舍III.md

This commit is contained in:
Baturu
2021-06-06 21:02:20 -07:00
committed by GitHub
parent d268469c22
commit 74d0613666

View File

@ -287,6 +287,25 @@ class Solution {
Python
> 动态规划
```python
class Solution:
def rob(self, root: TreeNode) -> int:
result = self.robTree(root)
return max(result[0], result[1])
#长度为2的数组0不偷1
def robTree(self, cur):
if not cur:
return (0, 0) #这里返回tuple, 也可以返回list
left = self.robTree(cur.left)
right = self.robTree(cur.right)
#偷cur
val1 = cur.val + left[0] + right[0]
#不偷cur
val2 = max(left[0], left[1]) + max(right[0], right[1])
return (val2, val1)
```
Go