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.git
Determine the maximum amount of money the thief can rob tonight without alerting the police.github
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:ide
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.
在上次打劫完一條街道以後和一圈房屋後,小偷又發現了一個新的可行竊的地區。這個地區只有一個入口,咱們稱之爲「根」。 除了「根」以外,每棟房子有且只有一個「父「房子與之相連。一番偵察以後,聰明的小偷意識到「這個地方的全部房屋的排列相似於一棵二叉樹」。 若是兩個直接相連的房子在同一天晚上被打劫,房屋將自動報警。ui
計算在不觸動警報的狀況下,小偷一晚可以盜取的最高金額。this
示例 1:code
輸入: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 輸出: 7 解釋: 小偷一晚可以盜取的最高金額 = 3 + 3 + 1 = 7.
示例 2:orm
輸入: [3,4,5,1,3,null,1] 3 / \ 4 5 / \ \ 1 3 1 輸出: 9 解釋: 小偷一晚可以盜取的最高金額 = 4 + 5 = 9.
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-04-07 10:43:47 # @Last Modified by: 何睿 # @Last Modified time: 2019-04-07 11:00:22 class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ return max(self.recursion(root)) def recursion(self, root): # result[0] 表示偷當前的房子,result[1] 表示不偷當前的房子 if not root: return [0, 0] result = [0, 0] left = self.recursion(root.left) right = self.recursion(root.right) # 偷當前的房子:result[0] :當前節點的值+ 左右子樹中不偷根節點房子的最大值 result[0] = root.val + left[1] + right[1] # 不偷當前的房子:result[1] 那麼左右子樹的根節點偷不偷均可以,選最大值 result[1] = max(left[0], left[1]) + max(right[0], right[1]) return result