What's problem with my python code? Why Time Limit Exceeded?

  • 0
    # 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):
            if root is None:
                return 0
            return max(self.robInclude(root), self.robExclude(root))
        def robInclude(self, node):
            if node is None:
                return 0
            return self.robExclude(node.left) + self.robExclude(node.right) + node.val
        def robExclude(self, node):
            if node is None:
                return 0
            return self.rob(node.left) + self.rob(node.right)

  • 0

    Try to do this with memorization, the problem can be optimized using dynamic programming because the problem contains similar repeated subproblem calculations.

Log in to reply

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