前序遍历:
class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: self.res=[] def dfs(root): if not root: return None self.res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return self.res
中序遍历:
class Solution: def midorderTraversal(self, root: Optional[TreeNode]) -> List[int]: self.res=[] def dfs(root): if not root: return None dfs(root.left) self.res.append(root.val) dfs(root.right) dfs(root) return self.res
后序遍历:
class Solution: def backorderTraversal(self, root: Optional[TreeNode]) -> List[int]: self.res=[] def dfs(root): if not root: return None dfs(root.left) dfs(root.right) self.res.append(root.val) dfs(root) return self.res
层序遍历:
class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: res=[] if not root: return res queue=[root] while queue: size=len(queue) tmp=[] for _ in range(size): r=queue.pop(0) tmp.append(r.val) if r.left: queue.append(r.left) if r.right: queue.append(r.right) res.append(tmp) return res