The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
Input: [3,2,3,null,3,null,1]
3 / \ 2 3 \ \ 3 1
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: [3,4,5,1,3,null,1]
3 / \ 4 5 / \ \ 1 3 1
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
思路:
和上两题不同的是:本题是二叉树形状,树中直接相连(父子节点)不能同时打劫。我们不难找到规律:这里可以按根结点是否打劫分为两种情况:(1)如果根结点被打劫,那么意味着它的子节点都不能打劫,需要直接打劫其孙子辈节点;(2)如果根结点不打劫,那么可以考虑其左右孩子。同时,由于树的特性,左右子树都是子问题,因此实际上就是两种情况分别递归。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val,left=None,right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def rob(self, root: TreeNode) -> int:
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
res1 = 0
res2 = 0
# 根结点不打劫
res1 += root.val
if root.right is not None:
res1 += self.rob(root.right.right)+self.rob(root.right.left)
if root.left is not None:
res1 += self.rob(root.left.right)+self.rob(root.left.left)
# 根结点不打劫
res2 = self.rob(root.left)+self.rob(root.right)
return max(res1,res2)
root = TreeNode(3,TreeNode(2,right=TreeNode(3)),TreeNode(3,right=TreeNode(1))) #二叉树的创建
solutin = Solution()
solutin.rob(root)
递归+动态规划:
在递归中进行动态规划的过程,在递归的每一层返回两个值,一个值代表对当前node进行rob的结果,另一个值代表不对当前node进行rob的结果。如果rob当前的node,那么当前node的children node不能rob。反之,当前node的children node能rob,取进行rob和不进行rob中的最大值。应该递推方程为:
这种方法不是很好理解
#not rob current node
case0 = max(rob_leftchild,notrob_leftchild) + max(rob_rightchild,notrob_rightchild)
#rob current node
case1 = node.val + notrob_leftchild + notrob_rightchild
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val,left=None,right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rob(self, root: TreeNode) -> int:
"""
:type root: TreeNode
:rtype: int
"""
def robchild(node):
if not node:
return [0,0]
left = robchild(node.left)
right = robchild(node.right)
curr_res = [0,0]
#not rob curr level
curr_res[0] = max(left[0],left[1])+max(right[0],right[1])
#rob curr_level
curr_res[1] = node.val+left[0]+right[0]
return curr_res
ans = robchild(root)
return max(ans)
root = TreeNode(3,TreeNode(2,right=TreeNode(3)),TreeNode(3,right=TreeNode(1))) #二叉树的创建
solutin = Solution()
solutin.rob(root)