给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
递归法
# 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: TreeNode) -> List[int]:
if not root:
return []
res = []
if root:
res = res + self.postorderTraversal(root.left)
res = res + self.postorderTraversal(root.right)
res.append(root.val)
return res
迭代法: 将节点放入中间存储栈中,然后节点弹出作为当前节点,当前节点的值加入到res里面,注意:后序遍历师先左再右后根,列表中节点的插入顺序是根右左(先添加根,为了弹出的时候先弹出右,list中先添加左后右,则弹出时:先右后左),返回结果时将列表中的结果反转即为左右根
# 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: TreeNode) -> List[int]:
res = []
if not root:
return res
stack = [root]
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return res[::-1]