Likou 337. Robbery III

Topic source: 337. Robbery III
Topic: The thief has discovered a new robbery area. There is only one entrance to this area, which we call root.

Apart from root, each house has one and only one "parent" house connected to it. After some reconnaissance, the clever thief realized that "all the houses in this place are arranged like a binary tree". If two directly connected houses are robbed on the same night, the houses will automatically call the police.

The root of the given binary tree. Returns the maximum amount a thief can steal without triggering the alarm.
insert image description here
insert image description here
Idea: Dynamic programming Through the method of subsequent traversal, each time the optimal value of the current node is found, and then the binary tree is traversed in turn to obtain the final optimal value, that is, the highest amount stolen by the thief.
One thing to note in the middle is that two spaces are created to store the node robbery or no robbery. If robbery, the optimal value of the current node is equal to the optimal value of the left subtree without robbery + the optimal value of the right subtree without robbery + the value of the current node ; if not robbed, the optimal value of the current node is equal to The maximum value of robbery or no robbery in the left subtree + the maximum value of robbery or no robbery in the right subtree (because the current node does not know whether the left and right subtrees are robbed or not, so only two cases of robbery or no robbery can be taken. max)
python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def dps(root):
            if not root:
                return [0, 0]
            ans = [0, 0]
            # 左子树打劫以后的情况
            left = dps(root.left)
            #右子树打劫以后的情况
            right = dps(root.right)
            ans[0] = max(left[0], left[1]) + max(right[0], right[1])
            ans[1] = left[0] + right[0] + root.val
            return ans
        ans = dps(root)
        return max(ans[0], ans[1])

insert image description here
Reference link: LeetCode 337. Fighting the family III | Python
[Leetcode] Python version of the daily question (20200805): 337. The family robbery III (dynamic programming on the tree)
force buckle topic 337-The family robbery III

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324340690&siteId=291194637