递归+迭代:迭代方法,采用了逆向思维,按照中右左的思想从上到下进行结果获取,最终逆置,就形成了后序遍历的结果,真实开挂啊!
# 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]
"""
###############迭代###################
if not root:
return []
res = list()
stack = [root,]
while stack:
tmp = stack.pop()
res.append(tmp.val)
if tmp.left:
stack.append(tmp.left)
if tmp.right:
stack.append(tmp.right)
return res[::-1]
################递归##################
if not root:
return []
res = list()
def helper(node):
if node.left:
helper(node.left)
if node.right:
helper(node.right)
res.append(node.val)
helper(root)
return res