LeetCode337 打家劫舍 III

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))

posted on 2022-07-01 17:10  solvit  阅读(14)  评论(0编辑  收藏  举报

导航