# 前序遍历之递归classSolution:defpreorderTraversal(self, root: TreeNode)-> List[int]:ifnot root:return[]
res =[]deffunc(root):ifnot root:return
res.append(root.val)
func(root.left)
func(root.right)
func(root)return res
# 前序遍历之迭代classSolution:defpreorderTraversal(self, root: TreeNode)-> List[int]:ifnot root:return[]
stack =[root]
res =[]while stack:
temp = stack.pop()
res.append(temp.val)if temp.right:
stack.append(temp.right)if temp.left:
stack.append(temp.left)return res
# 中序遍历之递归classSolution:definorderTraversal(self, root: TreeNode)-> List[int]:ifnot root:return[]deffunc(root):ifnot root:return
func(root.left)
res.append(root.val)
func(root.right)
res =[]
func(root)return res
# 中序遍历之迭代classSolution:definorderTraversal(self, root: TreeNode)-> List[int]:ifnot root:return[]
stack =[]
cur = root
res =[]while cur or stack:while cur:
stack.append(cur)
cur = cur.left
temp = stack.pop()
res.append(temp.val)if temp.right:
cur = temp.right
return res
# 前序遍历之递归class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] def func(root): if not root: return res.append(root.val)