# Dynamic programming
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
from collections import defaultdict
if root is None:
return 0
self.dp1 = defaultdict(int) # rob current point
self.dp2 = defaultdict(int) # do not rob current point
self.dfs(root)
return max(self.dp1[root], self.dp2[root])
def dfs(self, root):
if root.left is not None:
self.dfs(root.left)
if root.right is not None:
self.dfs(root.right)
self.dp1[root] = root.val + self.dp2[root.left] + self.dp2[root.right]
self.dp2[root] = (max(self.dp1[root.left], self.dp2[root.left])
+ max(self.dp1[root.right], self.dp2[root.right]))