Traversal of Binary Tree
本文讨论了二叉树的各种遍历。
This blog discusses about all kinds of traversals in the binary tree.
如何遍历一棵树
通常来说,树的遍历有2种方式
Breadth First Search (BFS) 宽度优先搜索
树的层次遍历,先遍历完一层然后再遍历下一层。
Depth First Search (DFS) 深度优先搜索
树的先序遍历、中序遍历和后序遍历都是 DFS,具体的实现方式可以有两种
- Recursion: 隐式地调用了栈
- Iterative: 用栈或者队列来实现
Tree Transverse
定义二叉树节点类
1 | # Definition of TreeNode |
Binary Tree Preorder Traversal
Recursion Approach
1 | def preorderTraversal(root: TreeNode): |
Iterative Approach
1 |
Binary Tree Inorder Traversal
Recursion Approach
1 | def inorderTraversal(root: TreeNode): |
Iterative Approach
1 |
Binary Tree Postorder Traversal
Recursion Approach
1 | def postorderTraversal(root: TreeNode): |
Iterative Approach
1 |
Binary Tree Level Order Traversal
Iterative Approach
1 |