The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.
Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
Constraints:
The number of nodes in the tree is in the range [1, 10⁴].
0 <= Node.val <= 10⁴
Test Cases
1 2 3 4 5 6 7 8
# 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 classSolution: defrob(self, root: Optional[TreeNode]) -> int:
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from _utils.binary_tree import build_tree from solution import Solution from solution2 import Solution as Solution2 from solution3 import Solution as Solution3
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
max2 = lambda a, b: a if a >= b else b val = lambda u: u.val if u else0 stack = [] prev = None node = root while node or stack: if node: stack.append(node) node = node.left elif stack[-1].right != prev: node = stack[-1].right prev = None else: prev = stack.pop() # prev is the LRN visiting node, its left and right child both done. if prev.left: prev.val += val(prev.left.left) + val(prev.left.right) if prev.right: prev.val += val(prev.right.left) + val(prev.right.right) prev.val = max2(prev.val, val(prev.left) + val(prev.right))
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
max2 = lambda a, b: a if a >= b else b dp = lambda u: u.val if u else (0, 0) stack = [] prev = None node = root while node or stack: if node: stack.append(node) node = node.left elif stack[-1].right != prev: node = stack[-1].right prev = None else: prev = stack.pop() # prev is the LRN visiting node, its left and right child both done. prev.val = ( prev.val + dp(prev.left)[1] + dp(prev.right)[1], max2(*dp(prev.left)) + max2(*dp(prev.right)), )