Skip to content

Commit 3d077ce

Browse files
committed
打劫房屋 III
1 parent ee4b65f commit 3d077ce

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

house_robber_iii.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param {TreeNode} root, the root of binary tree.
5+
# @return {int} The maximum amount of money you can rob tonight
6+
def houseRobber3(self, root):
7+
# write your code here
8+
# 递归!比较该节点抢和不抢的最大值。
9+
return max(self._houseRobber3(root))
10+
11+
def _houseRobber3(self, root):
12+
if not root:
13+
return (0, 0)
14+
rob_left = self._houseRobber3(root.left)
15+
rob_right = self._houseRobber3(root.right)
16+
not_rob = rob_left[1] + rob_right[1] + root.val
17+
rob = max(rob_left) + max(rob_right)
18+
return (not_rob, rob)

0 commit comments

Comments
 (0)