"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# write your code here
if root is None:
return []
stack = [root]
postorderResult = []
prev = None
curr = None
while stack:
curr = stack[-1]
if prev is None or prev.left == curr or prev.right == curr: # traverse down the tree
if curr.left:
stack.append(curr.left)
elif curr.right: #非常重要,如果左子树为空的时候,这时候才能考虑是从右面过来的。
stack.append(curr.right)
elif curr.left == prev: # traverse up from the left of the tree then need to go to right
if curr.right:
stack.append(curr.right)
else: # the end of node will be added when prev == curr , that means the end.
postorderResult.append(curr.val)
stack.pop()
prev = curr
return postorderResult