LC 144 二叉树的前序遍历
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#递归
res = []
def traversal(root:TreeNode):
if root == None:
return
res.append(root.val) #中
traversal(root.left)#左
traversal(root.right)#右
traversal(root)
return res
#迭代
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val) #中
if node.right:
stack.append(node.right) #右
if node.left:
stack.append(node.left) #左
return res
LC 94 二叉树的中序遍历
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#递归
res = []
def traversal(root:TreeNode):
if root == None:
return
traversal(root.left) #左
res.append(root.val) #中
traversal(root.right) #右
traversal(root)
return res
# 迭代
if not root:
return []
stack = []
res = []
cur = root
while cur or stack:
#先迭代访问最底层的左子树结点
if cur:
stack.append(cur)
cur = cur.left
# 到达最左结点后处理栈顶结点
else:
cur = stack.pop()
res.append(cur.val)
# 取栈顶元素右结点
cur = cur.right
return res
LC 145 二叉树的后序遍历
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#递归
res = []
def traversal(root:TreeNode):
if root == None:
return
traversal(root.left) #左
traversal(root.right) #右
res.append(root.val) #中
traversal(root)
return res
#迭代
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val) #中
if node.right:
stack.append(node.right) #右
if node.left:
stack.append(node.left) #左
return res[::-1] #反转数组
递归:确定递归函数的参数和返回值-- 确定终止条件-- 确定单层递归的逻辑
迭代:由于栈是先进后出,所以注意顺序的变化。
前序:中左右; 中序:左中右 后序:左右中