DeepRest

House Robber III

Dec 8th, 2021 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.     def rob(self, root: Optional[TreeNode]) -> int:
  9.         #function returns a tuple (e1, e2) where e1 is amt robbed including the subtree's root while e2 is amt without subtree's root
  10.         def help(root):
  11.             if not root:
  12.                 return (0, 0)
  13.             #postorder
  14.             a,b = help(root.left)
  15.             c, d = help(root.right)
  16.             return(b+d+root.val,max(a, b)+max(c,d))
  17.         return max(help(root))
Add Comment
Please, Sign In to add comment