mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0337.打家劫舍III.md
This commit is contained in:
@ -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:
|
||||
|
||||
|
Reference in New Issue
Block a user