337. 打家劫舍III (二叉树)

题目

337. 打家劫舍III (二叉树)_第1张图片

题解

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        memo = dict()
        if not root:
            return 0
        if root in memo:
            return memo[root]
        do_rob = root.val
        if root.left:
            do_rob += self.rob(root.left.left)
            do_rob += self.rob(root.left.right)
        if root.right:
            do_rob += self.rob(root.right.left)
            do_rob += self.rob(root.right.right)

        not_do_rob = self.rob(root.left) + self.rob(root.right)
        res = max(do_rob, not_do_rob)
        memo[root] = res

        return res

你可能感兴趣的:(LeetCode,python,leetcode,动态规划,算法,笔记)