1 递归
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def tarversal(root):
if root == None:
return
tarversal(root.left)
tarversal(root.right)
res.append(root.val)
tarversal(root)
return res
2 迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# 后续遍历顺序是左右中
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
# 左先进栈,右再进
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# 从中右左的顺序翻转至左中右
return res[ : : -1]