【LeetCode】337. House Robber |||

337. House Robber |||

Description:

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)递归法:

【LeetCode】337. House Robber |||_第1张图片

关于树的问题,首先想到的是用递归法求解。针对每一个树节点我们给定一个长度为2的result列表。result[0]表示不抢劫当前节点能取到的最大值;result[1]表示抢劫当前节点能取到的最大值。

已经AC的代码:

# Definition for a binary tree node.
class TreeNode(object):
    """节点类"""
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Tree(object):

    # 建立二叉树是以层序遍历方式输入,节点不存在时以 'None' 表示
    def creatTree(self, nodeList):
        if nodeList[0] == None:
            return None
        head = TreeNode(nodeList[0])
        Nodes = [head]
        j = 1
        for node in Nodes:
            if node != None:
                node.left = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
                Nodes.append(node.left)
                j += 1
                if j == len(nodeList):
                    return head
                node.right = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
                j += 1
                Nodes.append(node.right)
                if j == len(nodeList):
                    return head

class Solution:

    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return max(self.tryRob(root))

    def tryRob(self, node):
        if node == None:
            return [0, 0]
        # result[0] is max value if not rob current node
        # result[1] is max value if rob current node
        result = [0] * 2
        left_val = self.tryRob(node.left)
        right_val = self.tryRob(node.right)
        result[0] = max(left_val[0], left_val[1]) + max(right_val[0], right_val[1])
        result[1] = left_val[0] + right_val[0] + node.val
        return result

if __name__ == "__main__":
    elements = [3, 4, 5, 1, 3, None, 1]
    tree = Tree()
    head = tree.creatTree(elements)
    solution = Solution()
    print("result:{}".format(solution.rob(head)))

Reference:

【1】Python --- 二叉树的层序建立与三种遍历:https://www.cnblogs.com/tomhawk/p/7464639.html

【2】House Robber |/||/|||:http://v.youku.com/v_show/id_XMjg3ODQwMjk0MA==.html?spm=a2h0j.11185381.listitem_page1.5~A

你可能感兴趣的:(算法,LeetCode)