LeetCode337:House Robber III

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.

LeetCode:链接

本题的做法,就是求本节点+孙子更深节点 vs 儿子节点+重孙更深节点的比较

用了dfs函数,虽然递归是自顶向下的,但因为是不断的return,所以真正求值是从底向上的。用到了一个有两个元素的列表,分别保存了之前层的,不取节点和取节点的情况。然后遍历左右子树,求出当前节点取和不取能得到的值,再返回给上一层。注意这个里面的robcurr是当前节点能达到的最大值,所以最后返回结果的时候试试返回的root节点robcurr的值

# 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 dfs(root):
            if not root:
                return [0, 0]
            # 偷左边的
            robleft = dfs(root.left)
            # 偷右边的
            robright = dfs(root.right)
            # 如果不偷当前节点 左右子树节点相加
            nonrob = robleft[1] + robright[1]
            # 如果偷当前结点 左右子树的节点就不能加 同时和不偷相比 保留最大值
            rob = max(root.val + robleft[0] + robright[0], nonrob)
            return [nonrob, rob]
        return dfs(root)[1]


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值