Binary Tree Traversal 二元樹走訪
🐳 Definition
在 leetcode 的教學當中,樹的定義如下:
A
treeis a frequently-used data structure to simulate a hierarchical tree structure.
Each node of the tree will have a root value and a list of references to other nodes which are called child nodes. From graph view, a tree can also be defined as a directed acyclic graph which has
N nodesandN-1 edges.
二元樹的定義如下:
A
Binary Treeis one of the most typical tree structure. As the name suggests, a binary tree is a tree data structure in which each node hasat most two children, which are referred to as the left child and the right child.
簡單來說,如果將二元樹畫成圖的話,會長得像下面的樣子:
graph TB
    A((1))-->B((2))
    A-->C((3))
    B-->D((4))
    B-->E((5))
    C-->F((6))
    C-->G((7))
    D-->H((8))
    D-->I((9))
    E-->J((10))
🐳 How to Traverse A Tree
與二元樹相關最常見的 leetcode 題就是如何遍歷二元樹了,遍歷指的是在不重複的情況下,存取樹的所有節點。目前有四種方式可以遍歷二元樹:
🦀 Pre-order Traversal
Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree.
遍歷二元樹的順序:
- 中
- 左
- 右
用 javascript 來實作 Pre-order Traversal:
| 1 | /** | 
🦀 In-order Traversal
In-order traversal is to traverse the left subtree first. Then visit the root. Finally, traverse the right subtree.
順序:
- 左
- 中
- 右
用 javascript 來實作 In-order Traversal:
| 1 | /** | 
🦀 Post-order Traversal
Post-order traversal is to traverse the left subtree first. Then traverse the right subtree. Finally, visit the root.
順序:
- 左
- 右
- 中
用 javascript 來實作 Post-order Traversal:
| 1 | /** | 
樹(tree)裡面的每一個節點(node)都要按照上面提到的順序來遍歷才算完成。
🦀 Level Order Traversal
Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
以下面的 Binary Tree 為例:
graph TB
    A((3))-->B((9))
    A-->C((20))
    C-->D((15))
    C-->E((7))
遍歷的順序會是:3 > 9 > 20 > 15 > 7。
用 javascript 來實作 Level Order Traversal:
| 1 | 初步想法: | 
| 1 | /** | 
除了使用遞迴來實作走訪二元樹之外,也可以使用 BFS(廣度優先搜尋演算法) 和 DFS(深度優先搜尋演算法)。
