Created
December 8, 2018 21:40
-
-
Save jianminchen/f63abd8bbeb6ec3fd74bb5486b20f570 to your computer and use it in GitHub Desktop.
Post order iterative - final code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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