Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 8, 2018 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f63abd8bbeb6ec3fd74bb5486b20f570 to your computer and use it in GitHub Desktop.
Save jianminchen/f63abd8bbeb6ec3fd74bb5486b20f570 to your computer and use it in GitHub Desktop.
Post order iterative - final code
#The interviewee went over the example of tree, explained the algorithm to me.
1
/ \
2 3
\
4
/
5
#After the visit:
# 1
#
# 2 3
#
# 4
#
# 5
#
#stack =
#res = [5,4,2,3,1]
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = [root]
res = []
while stack:
s = stack[-1]
if s.left:
stack.append(s.left)
s.left = None
elif s.right:
stack.append(s.right)
s.right = None
else:
res.append(stack.pop())
return res
# stack1 = [root]
# stack2 = []
# while stack1:
# node = stack1.pop()
# if node:
# stack2.append(node.left)
# stack2.append(node.right)
# return stack2[::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment