Both are almost same codes for House Robber III in leetcode but one is time limit exceed code whereas other is perfect solution to the question

Question:

The correct code is

class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        def dfs(root):
            if not root:
                return [0,0]
            leftpair=dfs(root.left)
            rightpair=dfs(root.right)
            withroot=root.val+leftpair[1]+rightpair[1]
            withoutroot=max(leftpair)+max(rightpair)
            return [withroot,withoutroot]
                
        
        return max(dfs(root))          
                

The code which is leading to time limit exceeded error in leetcode is

class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        def dfs(root):
            if not root:
                return [0,0]
            
            left=root.val+dfs(root.left)[1]+dfs(root.right)[1]
            right=max(dfs(root.left))+max(dfs(root.right))
            return [left,right]
                
        return max(dfs(root))        

I don’t think there is any difference in time complexities of above two code. Can someone help me with this ??

Asked By: Anusha Yerram

||

Answers:

The first version of dfs calls itself recursively twice, saving the results and reusing them. Here are the two recursive calls:

leftpair=dfs(root.left)
rightpair=dfs(root.right)

The second version of dfs calls itself recursively four times. Here are the four recursive calls, embedded in expressions:

left=root.val+dfs(root.left)[1]+dfs(root.right)[1]
right=max(dfs(root.left))+max(dfs(root.right))

As you can see, rather than reusing the results of the recursive calls, it instead repeats the calls (twice with root.left and twice with root.right). Understandably, this results in a significantly longer tuntime.

Answered By: Tom Karzes
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.