递归和非递归两种方法:
递归:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ans = []
if root==None:
return ans
self.postTraverse(root, ans)
return ans
def postTraverse(self, t, ans):
if t:
self.postTraverse(t.left, ans)
self.postTraverse(t.right, ans)
ans.append(t.val)
非递归:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ans = []
if root==None:
return ans
mark = [0]*101
stack = []
p = root
while(p or len(stack)):
if p:
stack.append(p)
mark[len(stack)-1] = 0
p = p.left
else:
if mark[len(stack)-1]==0:
mark[len(stack)-1] = 1
p = stack[-1]
p = p.right
else:
q = stack[-1]
ans.append(q.val)
stack.pop(-1)
return ans