337. 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.

思路

类似House Robber I,不过这里用recursive的方法,每个被延伸到的node都返回一个tuple, 类似由pre, cur = cur, max(cur, pre+nums[i])后的pre和cur
先判断base case,如果不是root,返回(0, 0)
否则,一直向左右延伸;又因为每次都有返回值,所以用一个在延伸时,用一个变量把值存起来,用于后面返回值的计算

class Solution:
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.test(root)[1]
        
    def test(self, root):
        if not root:
            return (0,0)
        if (root):
            l = self.test(root.left)
            r = self.test(root.right)
            return (l[1]+r[1], max(l[1]+r[1], l[0]+r[0]+root.val))

你可能感兴趣的:(337. House Robber III)