House Robber III

House Robber III

DFS 版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node):
if not node: return 0, 0
l, r = dfs(node.left), dfs(node.right)
return max(l) + max(r), node.val + l[0] + r[0]
return max(dfs(root))

leet code