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.
solved 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 [closed]