原题链接:https://leetcode-cn.com/problems/house-robber-iii/。
解题思路:
因为所有的房屋按照二叉树的结构排布。不能同时抢相邻层的房间。
利用递归的思想求解这个题。
如果小偷偷了第i层,那么就不可以抢第i+1层。
建立一个有两个元素的列表,第一个元素存储不抢这一层的获得的最高金额。第二个元素存储抢这一层获得的最高金额。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def treerob(root):
res = [0]*2
if not root:
return res
left = treerob(root.left) # 入口为root.left时,获得最大金额
right = treerob(root.right) # 入口为root.right时,获得最大金额
res[0] = max(left[0],left[1])+max(right[0],right[1])
res[1] = root.val + left[0] + right[0]
return res
res = treerob(root)
return max(res)