LeetCode337. 打家劫舍 III(DFS记忆化搜索)

LeetCode337. 打家劫舍 III(DFS记忆化搜索)

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def rob(self, root: 'TreeNode') -> 'int':
        ans = self.dfs(root)
        return max(ans[0], ans[1])

    def dfs(self, bt: TreeNode):
        ans = [0, 0]
        if not bt:
            return ans
        left = self.dfs(bt.left)
        right = self.dfs(bt.right)
        ans[0] = max(left[0], left[1]) + max(right[0], right[1])
        ans[1] = bt.val + left[0] + right[0]
        return ans

你可能感兴趣的:(Python,DFS,LeetCode,algorithm)