7 Line DFS + Dictionary Python


  • 0
    class Solution(object):
        def rob(self, root):
            dic = {(None, 0): 0, (None, 1): 0}
            def mark(r, canvisit):
                if (r, canvisit) in dic:
                    return dic[(r, canvisit)]
                dic[(r, canvisit)] = max(r.val + mark(r.left, 0) + mark(r.right, 0), mark(r.left, 1) + mark(r.right, 1) ) if canvisit else mark(r.left, 1) + mark(r.right, 1) 
                return dic[(r, canvisit)]
            return max( mark(root, 0), mark(root, 1) )
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.