Reputation: 97
I am a python newbie -.- The following code is what I write on leetcode:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result, stack, current, last_traversed = [], [], root, None
while stack or current:
if current:
stack.append(current)
current = current.left
else:
parent = stack[-1]
if parent.right in (None, last_traversed):
result.append(parent.val)
last_traversed = stack.pop()
else:
current = parent.right
return result
It works apparently, but I used to replace all parent
with current
and the program gives me the result of "Time Limit Exceeded".
What I was wondering is why I can't simply use current
throughout the code. Why I have to create another variable for the parent node?
Upvotes: 1
Views: 57
Reputation: 5534
If stack is true, current is False and stack[-1].right is one among None and last_traversed you don't want current to be modified.
This is a question about the algorithm, not about the language.
Upvotes: 1
Reputation: 13576
In the branch that begins with if parent.right
, parent
is set but current
is not. So if you replace it with current
the behavior is different.
Upvotes: 2