分类:二叉树-二叉树的遍历
题目描述:给定一个二叉树,返回它的 后序 遍历。
解题思路:
递归:
# 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]: 递归 def postorder(root:TreeNode): if not root: return [] postorder(root.left) postorder(root.right) res.append(root.val) res = [] postorder(root) return res
迭代:
# 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,stack = [],[root] prev = root # 为了判断父子节点关系 while len(stack): root = stack.pop()# 取出一个节点,表示开始访问以该节点为根的子树 if (not root.right and not root.left ) or ( root.right ==prev or root.left == prev): # 如果该节点为叶子节点,或者已经访问该节点的子节点 res.append(root.val) # 直接访问 prev = root else:# 否则就顺序把当前节点,右孩子,左孩子入栈 stack.append(root) if root.right: stack.append(root.right) if root.left: stack.append(root.left) return res
# 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,stack=[],[] prev = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() # 比前序和中序的模板增加一个判断过程:节点没有右孩子或已经访问了该节点的子节点 if not root.right or root.right == prev: res.append(root.val) prev = root root = None else: stack.append(root) root = root.right return res