LeetCode337 打家劫舍 III
与LeetCode198 打家劫舍一致,将数列换为树形结构
# 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: TreeNode) -> int:
def dfs(root):
if root is None: return 0, 0
left, sub_left = dfs(root.left)
right, sub_right = dfs(root.right)
cur = root.val + sub_left + sub_right
sub_cur = left + right
return max(cur, sub_cur), sub_cur
return max(dfs(root))