题目
题解
# 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