mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-13 23:56:07 +00:00
build
This commit is contained in:
@@ -2,25 +2,25 @@
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 7.2 Binary tree traversal
|
||||
# 7.2 Binary Tree Traversal
|
||||
|
||||
From a physical structure perspective, a tree is a data structure based on linked lists. Hence, its traversal method involves accessing nodes one by one through pointers. However, a tree is a non-linear data structure, which makes traversing a tree more complex than traversing a linked list, requiring the assistance of search algorithms.
|
||||
|
||||
The common traversal methods for binary trees include level-order traversal, pre-order traversal, in-order traversal, and post-order traversal.
|
||||
|
||||
## 7.2.1 Level-order traversal
|
||||
## 7.2.1 Level-Order Traversal
|
||||
|
||||
As shown in Figure 7-9, <u>level-order traversal</u> traverses the binary tree from top to bottom, layer by layer. Within each level, it visits nodes from left to right.
|
||||
|
||||
Level-order traversal is essentially a type of <u>breadth-first traversal</u>, also known as <u>breadth-first search (BFS)</u>, which embodies a "circumferentially outward expanding" layer-by-layer traversal method.
|
||||
Level-order traversal is essentially <u>breadth-first traversal</u>, also known as <u>breadth-first search (BFS)</u>, which embodies a "expanding outward circle by circle" layer-by-layer traversal method.
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 7-9 Level-order traversal of a binary tree </p>
|
||||
|
||||
### 1. Code implementation
|
||||
### 1. Code Implementation
|
||||
|
||||
Breadth-first traversal is usually implemented with the help of a "queue". The queue follows the "first in, first out" rule, while breadth-first traversal follows the "layer-by-layer progression" rule, the underlying ideas of the two are consistent. The implementation code is as follows:
|
||||
Breadth-first traversal is typically implemented with the help of a "queue". The queue follows the "first in, first out" rule, while breadth-first traversal follows the "layer-by-layer progression" rule; the underlying ideas of the two are consistent. The implementation code is as follows:
|
||||
|
||||
=== "Python"
|
||||
|
||||
@@ -30,15 +30,15 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
|
||||
# Initialize queue, add root node
|
||||
queue: deque[TreeNode] = deque()
|
||||
queue.append(root)
|
||||
# Initialize a list to store the traversal sequence
|
||||
# Initialize a list to save the traversal sequence
|
||||
res = []
|
||||
while queue:
|
||||
node: TreeNode = queue.popleft() # Queue dequeues
|
||||
node: TreeNode = queue.popleft() # Dequeue
|
||||
res.append(node.val) # Save node value
|
||||
if node.left is not None:
|
||||
queue.append(node.left) # Left child node enqueues
|
||||
queue.append(node.left) # Left child node enqueue
|
||||
if node.right is not None:
|
||||
queue.append(node.right) # Right child node enqueues
|
||||
queue.append(node.right) # Right child node enqueue
|
||||
return res
|
||||
```
|
||||
|
||||
@@ -50,16 +50,16 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
|
||||
// Initialize queue, add root node
|
||||
queue<TreeNode *> queue;
|
||||
queue.push(root);
|
||||
// Initialize a list to store the traversal sequence
|
||||
// Initialize a list to save the traversal sequence
|
||||
vector<int> vec;
|
||||
while (!queue.empty()) {
|
||||
TreeNode *node = queue.front();
|
||||
queue.pop(); // Queue dequeues
|
||||
queue.pop(); // Dequeue
|
||||
vec.push_back(node->val); // Save node value
|
||||
if (node->left != nullptr)
|
||||
queue.push(node->left); // Left child node enqueues
|
||||
queue.push(node->left); // Left child node enqueue
|
||||
if (node->right != nullptr)
|
||||
queue.push(node->right); // Right child node enqueues
|
||||
queue.push(node->right); // Right child node enqueue
|
||||
}
|
||||
return vec;
|
||||
}
|
||||
@@ -73,15 +73,15 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
|
||||
// Initialize queue, add root node
|
||||
Queue<TreeNode> queue = new LinkedList<>();
|
||||
queue.add(root);
|
||||
// Initialize a list to store the traversal sequence
|
||||
// Initialize a list to save the traversal sequence
|
||||
List<Integer> list = new ArrayList<>();
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode node = queue.poll(); // Queue dequeues
|
||||
TreeNode node = queue.poll(); // Dequeue
|
||||
list.add(node.val); // Save node value
|
||||
if (node.left != null)
|
||||
queue.offer(node.left); // Left child node enqueues
|
||||
queue.offer(node.left); // Left child node enqueue
|
||||
if (node.right != null)
|
||||
queue.offer(node.right); // Right child node enqueues
|
||||
queue.offer(node.right); // Right child node enqueue
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@@ -90,85 +90,266 @@ Breadth-first traversal is usually implemented with the help of a "queue". The q
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree_bfs.cs"
|
||||
[class]{binary_tree_bfs}-[func]{LevelOrder}
|
||||
/* Level-order traversal */
|
||||
List<int> LevelOrder(TreeNode root) {
|
||||
// Initialize queue, add root node
|
||||
Queue<TreeNode> queue = new();
|
||||
queue.Enqueue(root);
|
||||
// Initialize a list to save the traversal sequence
|
||||
List<int> list = [];
|
||||
while (queue.Count != 0) {
|
||||
TreeNode node = queue.Dequeue(); // Dequeue
|
||||
list.Add(node.val!.Value); // Save node value
|
||||
if (node.left != null)
|
||||
queue.Enqueue(node.left); // Left child node enqueue
|
||||
if (node.right != null)
|
||||
queue.Enqueue(node.right); // Right child node enqueue
|
||||
}
|
||||
return list;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree_bfs.go"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
func levelOrder(root *TreeNode) []any {
|
||||
// Initialize queue, add root node
|
||||
queue := list.New()
|
||||
queue.PushBack(root)
|
||||
// Initialize a slice to save traversal sequence
|
||||
nums := make([]any, 0)
|
||||
for queue.Len() > 0 {
|
||||
// Dequeue
|
||||
node := queue.Remove(queue.Front()).(*TreeNode)
|
||||
// Save node value
|
||||
nums = append(nums, node.Val)
|
||||
if node.Left != nil {
|
||||
// Left child node enqueue
|
||||
queue.PushBack(node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
// Right child node enqueue
|
||||
queue.PushBack(node.Right)
|
||||
}
|
||||
}
|
||||
return nums
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree_bfs.swift"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
func levelOrder(root: TreeNode) -> [Int] {
|
||||
// Initialize queue, add root node
|
||||
var queue: [TreeNode] = [root]
|
||||
// Initialize a list to save the traversal sequence
|
||||
var list: [Int] = []
|
||||
while !queue.isEmpty {
|
||||
let node = queue.removeFirst() // Dequeue
|
||||
list.append(node.val) // Save node value
|
||||
if let left = node.left {
|
||||
queue.append(left) // Left child node enqueue
|
||||
}
|
||||
if let right = node.right {
|
||||
queue.append(right) // Right child node enqueue
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree_bfs.js"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
function levelOrder(root) {
|
||||
// Initialize queue, add root node
|
||||
const queue = [root];
|
||||
// Initialize a list to save the traversal sequence
|
||||
const list = [];
|
||||
while (queue.length) {
|
||||
let node = queue.shift(); // Dequeue
|
||||
list.push(node.val); // Save node value
|
||||
if (node.left) queue.push(node.left); // Left child node enqueue
|
||||
if (node.right) queue.push(node.right); // Right child node enqueue
|
||||
}
|
||||
return list;
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree_bfs.ts"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
function levelOrder(root: TreeNode | null): number[] {
|
||||
// Initialize queue, add root node
|
||||
const queue = [root];
|
||||
// Initialize a list to save the traversal sequence
|
||||
const list: number[] = [];
|
||||
while (queue.length) {
|
||||
let node = queue.shift() as TreeNode; // Dequeue
|
||||
list.push(node.val); // Save node value
|
||||
if (node.left) {
|
||||
queue.push(node.left); // Left child node enqueue
|
||||
}
|
||||
if (node.right) {
|
||||
queue.push(node.right); // Right child node enqueue
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree_bfs.dart"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
List<int> levelOrder(TreeNode? root) {
|
||||
// Initialize queue, add root node
|
||||
Queue<TreeNode?> queue = Queue();
|
||||
queue.add(root);
|
||||
// Initialize a list to save the traversal sequence
|
||||
List<int> res = [];
|
||||
while (queue.isNotEmpty) {
|
||||
TreeNode? node = queue.removeFirst(); // Dequeue
|
||||
res.add(node!.val); // Save node value
|
||||
if (node.left != null) queue.add(node.left); // Left child node enqueue
|
||||
if (node.right != null) queue.add(node.right); // Right child node enqueue
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree_bfs.rs"
|
||||
[class]{}-[func]{level_order}
|
||||
/* Level-order traversal */
|
||||
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
|
||||
// Initialize queue, add root node
|
||||
let mut que = VecDeque::new();
|
||||
que.push_back(root.clone());
|
||||
// Initialize a list to save the traversal sequence
|
||||
let mut vec = Vec::new();
|
||||
|
||||
while let Some(node) = que.pop_front() {
|
||||
// Dequeue
|
||||
vec.push(node.borrow().val); // Save node value
|
||||
if let Some(left) = node.borrow().left.as_ref() {
|
||||
que.push_back(left.clone()); // Left child node enqueue
|
||||
}
|
||||
if let Some(right) = node.borrow().right.as_ref() {
|
||||
que.push_back(right.clone()); // Right child node enqueue
|
||||
};
|
||||
}
|
||||
vec
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree_bfs.c"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
int *levelOrder(TreeNode *root, int *size) {
|
||||
/* Auxiliary queue */
|
||||
int front, rear;
|
||||
int index, *arr;
|
||||
TreeNode *node;
|
||||
TreeNode **queue;
|
||||
|
||||
/* Auxiliary queue */
|
||||
queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_SIZE);
|
||||
// Queue pointer
|
||||
front = 0, rear = 0;
|
||||
// Add root node
|
||||
queue[rear++] = root;
|
||||
// Initialize a list to save the traversal sequence
|
||||
/* Auxiliary array */
|
||||
arr = (int *)malloc(sizeof(int) * MAX_SIZE);
|
||||
// Array pointer
|
||||
index = 0;
|
||||
while (front < rear) {
|
||||
// Dequeue
|
||||
node = queue[front++];
|
||||
// Save node value
|
||||
arr[index++] = node->val;
|
||||
if (node->left != NULL) {
|
||||
// Left child node enqueue
|
||||
queue[rear++] = node->left;
|
||||
}
|
||||
if (node->right != NULL) {
|
||||
// Right child node enqueue
|
||||
queue[rear++] = node->right;
|
||||
}
|
||||
}
|
||||
// Update array length value
|
||||
*size = index;
|
||||
arr = realloc(arr, sizeof(int) * (*size));
|
||||
|
||||
// Free auxiliary array space
|
||||
free(queue);
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_tree_bfs.kt"
|
||||
[class]{}-[func]{levelOrder}
|
||||
/* Level-order traversal */
|
||||
fun levelOrder(root: TreeNode?): MutableList<Int> {
|
||||
// Initialize queue, add root node
|
||||
val queue = LinkedList<TreeNode?>()
|
||||
queue.add(root)
|
||||
// Initialize a list to save the traversal sequence
|
||||
val list = mutableListOf<Int>()
|
||||
while (queue.isNotEmpty()) {
|
||||
val node = queue.poll() // Dequeue
|
||||
list.add(node?._val!!) // Save node value
|
||||
if (node.left != null)
|
||||
queue.offer(node.left) // Left child node enqueue
|
||||
if (node.right != null)
|
||||
queue.offer(node.right) // Right child node enqueue
|
||||
}
|
||||
return list
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_tree_bfs.rb"
|
||||
[class]{}-[func]{level_order}
|
||||
### Level-order traversal ###
|
||||
def level_order(root)
|
||||
# Initialize queue, add root node
|
||||
queue = [root]
|
||||
# Initialize a list to save the traversal sequence
|
||||
res = []
|
||||
while !queue.empty?
|
||||
node = queue.shift # Dequeue
|
||||
res << node.val # Save node value
|
||||
queue << node.left unless node.left.nil? # Left child node enqueue
|
||||
queue << node.right unless node.right.nil? # Right child node enqueue
|
||||
end
|
||||
res
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
### 2. Complexity Analysis
|
||||
|
||||
```zig title="binary_tree_bfs.zig"
|
||||
[class]{}-[func]{levelOrder}
|
||||
```
|
||||
- **Time complexity is $O(n)$**: All nodes are visited once, using $O(n)$ time, where $n$ is the number of nodes.
|
||||
- **Space complexity is $O(n)$**: In the worst case, i.e., a full binary tree, before traversing to the bottom level, the queue contains at most $(n + 1) / 2$ nodes simultaneously, occupying $O(n)$ space.
|
||||
|
||||
### 2. Complexity analysis
|
||||
## 7.2.2 Preorder, Inorder, and Postorder Traversal
|
||||
|
||||
- **Time complexity is $O(n)$**: All nodes are visited once, taking $O(n)$ time, where $n$ is the number of nodes.
|
||||
- **Space complexity is $O(n)$**: In the worst case, i.e., a full binary tree, before traversing to the bottom level, the queue can contain at most $(n + 1) / 2$ nodes simultaneously, occupying $O(n)$ space.
|
||||
Correspondingly, preorder, inorder, and postorder traversals all belong to <u>depth-first traversal</u>, also known as <u>depth-first search (DFS)</u>, which embodies a "first go to the end, then backtrack and continue" traversal method.
|
||||
|
||||
## 7.2.2 Preorder, in-order, and post-order traversal
|
||||
Figure 7-10 shows how depth-first traversal works on a binary tree. **Depth-first traversal is like "walking" around the perimeter of the entire binary tree**, encountering three positions at each node, corresponding to preorder, inorder, and postorder traversal.
|
||||
|
||||
Correspondingly, pre-order, in-order, and post-order traversal all belong to <u>depth-first traversal</u>, also known as <u>depth-first search (DFS)</u>, which embodies a "proceed to the end first, then backtrack and continue" traversal method.
|
||||
{ class="animation-figure" }
|
||||
|
||||
Figure 7-10 shows the working principle of performing a depth-first traversal on a binary tree. **Depth-first traversal is like "walking" around the entire binary tree**, encountering three positions at each node, corresponding to pre-order, in-order, and post-order traversal.
|
||||
<p align="center"> Figure 7-10 Preorder, inorder, and postorder traversal of a binary tree </p>
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 7-10 Preorder, in-order, and post-order traversal of a binary search tree </p>
|
||||
|
||||
### 1. Code implementation
|
||||
### 1. Code Implementation
|
||||
|
||||
Depth-first search is usually implemented based on recursion:
|
||||
|
||||
@@ -176,7 +357,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
|
||||
```python title="binary_tree_dfs.py"
|
||||
def pre_order(root: TreeNode | None):
|
||||
"""Pre-order traversal"""
|
||||
"""Preorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: root node -> left subtree -> right subtree
|
||||
@@ -185,7 +366,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
pre_order(root=root.right)
|
||||
|
||||
def in_order(root: TreeNode | None):
|
||||
"""In-order traversal"""
|
||||
"""Inorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> root node -> right subtree
|
||||
@@ -194,7 +375,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
in_order(root=root.right)
|
||||
|
||||
def post_order(root: TreeNode | None):
|
||||
"""Post-order traversal"""
|
||||
"""Postorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> right subtree -> root node
|
||||
@@ -206,7 +387,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
=== "C++"
|
||||
|
||||
```cpp title="binary_tree_dfs.cpp"
|
||||
/* Pre-order traversal */
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
@@ -216,7 +397,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
preOrder(root->right);
|
||||
}
|
||||
|
||||
/* In-order traversal */
|
||||
/* Inorder traversal */
|
||||
void inOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
@@ -226,7 +407,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
inOrder(root->right);
|
||||
}
|
||||
|
||||
/* Post-order traversal */
|
||||
/* Postorder traversal */
|
||||
void postOrder(TreeNode *root) {
|
||||
if (root == nullptr)
|
||||
return;
|
||||
@@ -240,7 +421,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
=== "Java"
|
||||
|
||||
```java title="binary_tree_dfs.java"
|
||||
/* Pre-order traversal */
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode root) {
|
||||
if (root == null)
|
||||
return;
|
||||
@@ -250,7 +431,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
preOrder(root.right);
|
||||
}
|
||||
|
||||
/* In-order traversal */
|
||||
/* Inorder traversal */
|
||||
void inOrder(TreeNode root) {
|
||||
if (root == null)
|
||||
return;
|
||||
@@ -260,7 +441,7 @@ Depth-first search is usually implemented based on recursion:
|
||||
inOrder(root.right);
|
||||
}
|
||||
|
||||
/* Post-order traversal */
|
||||
/* Postorder traversal */
|
||||
void postOrder(TreeNode root) {
|
||||
if (root == null)
|
||||
return;
|
||||
@@ -274,124 +455,376 @@ Depth-first search is usually implemented based on recursion:
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_tree_dfs.cs"
|
||||
[class]{binary_tree_dfs}-[func]{PreOrder}
|
||||
/* Preorder traversal */
|
||||
void PreOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.Add(root.val!.Value);
|
||||
PreOrder(root.left);
|
||||
PreOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{InOrder}
|
||||
/* Inorder traversal */
|
||||
void InOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
InOrder(root.left);
|
||||
list.Add(root.val!.Value);
|
||||
InOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{binary_tree_dfs}-[func]{PostOrder}
|
||||
/* Postorder traversal */
|
||||
void PostOrder(TreeNode? root) {
|
||||
if (root == null) return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
PostOrder(root.left);
|
||||
PostOrder(root.right);
|
||||
list.Add(root.val!.Value);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_tree_dfs.go"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
func preOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
nums = append(nums, node.Val)
|
||||
preOrder(node.Left)
|
||||
preOrder(node.Right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
func inOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(node.Left)
|
||||
nums = append(nums, node.Val)
|
||||
inOrder(node.Right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
func postOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(node.Left)
|
||||
postOrder(node.Right)
|
||||
nums = append(nums, node.Val)
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="binary_tree_dfs.swift"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
func preOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.append(root.val)
|
||||
preOrder(root: root.left)
|
||||
preOrder(root: root.right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
func inOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root: root.left)
|
||||
list.append(root.val)
|
||||
inOrder(root: root.right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
func postOrder(root: TreeNode?) {
|
||||
guard let root = root else {
|
||||
return
|
||||
}
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root: root.left)
|
||||
postOrder(root: root.right)
|
||||
list.append(root.val)
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="binary_tree_dfs.js"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
function preOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.push(root.val);
|
||||
preOrder(root.left);
|
||||
preOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
function inOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root.left);
|
||||
list.push(root.val);
|
||||
inOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
function postOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root.left);
|
||||
postOrder(root.right);
|
||||
list.push(root.val);
|
||||
}
|
||||
```
|
||||
|
||||
=== "TS"
|
||||
|
||||
```typescript title="binary_tree_dfs.ts"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
function preOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.push(root.val);
|
||||
preOrder(root.left);
|
||||
preOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
function inOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root.left);
|
||||
list.push(root.val);
|
||||
inOrder(root.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
function postOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root.left);
|
||||
postOrder(root.right);
|
||||
list.push(root.val);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="binary_tree_dfs.dart"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.add(node.val);
|
||||
preOrder(node.left);
|
||||
preOrder(node.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
void inOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(node.left);
|
||||
list.add(node.val);
|
||||
inOrder(node.right);
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
void postOrder(TreeNode? node) {
|
||||
if (node == null) return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(node.left);
|
||||
postOrder(node.right);
|
||||
list.add(node.val);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="binary_tree_dfs.rs"
|
||||
[class]{}-[func]{pre_order}
|
||||
/* Preorder traversal */
|
||||
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
let mut result = vec![];
|
||||
|
||||
[class]{}-[func]{in_order}
|
||||
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
||||
if let Some(node) = root {
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
let node = node.borrow();
|
||||
res.push(node.val);
|
||||
dfs(node.left.as_ref(), res);
|
||||
dfs(node.right.as_ref(), res);
|
||||
}
|
||||
}
|
||||
dfs(root, &mut result);
|
||||
|
||||
[class]{}-[func]{post_order}
|
||||
result
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
let mut result = vec![];
|
||||
|
||||
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
||||
if let Some(node) = root {
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
let node = node.borrow();
|
||||
dfs(node.left.as_ref(), res);
|
||||
res.push(node.val);
|
||||
dfs(node.right.as_ref(), res);
|
||||
}
|
||||
}
|
||||
dfs(root, &mut result);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
let mut result = vec![];
|
||||
|
||||
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
|
||||
if let Some(node) = root {
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
let node = node.borrow();
|
||||
dfs(node.left.as_ref(), res);
|
||||
dfs(node.right.as_ref(), res);
|
||||
res.push(node.val);
|
||||
}
|
||||
}
|
||||
|
||||
dfs(root, &mut result);
|
||||
|
||||
result
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_tree_dfs.c"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
void preOrder(TreeNode *root, int *size) {
|
||||
if (root == NULL)
|
||||
return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
arr[(*size)++] = root->val;
|
||||
preOrder(root->left, size);
|
||||
preOrder(root->right, size);
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
void inOrder(TreeNode *root, int *size) {
|
||||
if (root == NULL)
|
||||
return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root->left, size);
|
||||
arr[(*size)++] = root->val;
|
||||
inOrder(root->right, size);
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
void postOrder(TreeNode *root, int *size) {
|
||||
if (root == NULL)
|
||||
return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root->left, size);
|
||||
postOrder(root->right, size);
|
||||
arr[(*size)++] = root->val;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="binary_tree_dfs.kt"
|
||||
[class]{}-[func]{preOrder}
|
||||
/* Preorder traversal */
|
||||
fun preOrder(root: TreeNode?) {
|
||||
if (root == null) return
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.add(root._val)
|
||||
preOrder(root.left)
|
||||
preOrder(root.right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
/* Inorder traversal */
|
||||
fun inOrder(root: TreeNode?) {
|
||||
if (root == null) return
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root.left)
|
||||
list.add(root._val)
|
||||
inOrder(root.right)
|
||||
}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
/* Postorder traversal */
|
||||
fun postOrder(root: TreeNode?) {
|
||||
if (root == null) return
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root.left)
|
||||
postOrder(root.right)
|
||||
list.add(root._val)
|
||||
}
|
||||
```
|
||||
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_tree_dfs.rb"
|
||||
[class]{}-[func]{pre_order}
|
||||
### Pre-order traversal ###
|
||||
def pre_order(root)
|
||||
return if root.nil?
|
||||
|
||||
[class]{}-[func]{in_order}
|
||||
# Visit priority: root node -> left subtree -> right subtree
|
||||
$res << root.val
|
||||
pre_order(root.left)
|
||||
pre_order(root.right)
|
||||
end
|
||||
|
||||
[class]{}-[func]{post_order}
|
||||
```
|
||||
### In-order traversal ###
|
||||
def in_order(root)
|
||||
return if root.nil?
|
||||
|
||||
=== "Zig"
|
||||
# Visit priority: left subtree -> root node -> right subtree
|
||||
in_order(root.left)
|
||||
$res << root.val
|
||||
in_order(root.right)
|
||||
end
|
||||
|
||||
```zig title="binary_tree_dfs.zig"
|
||||
[class]{}-[func]{preOrder}
|
||||
### Post-order traversal ###
|
||||
def post_order(root)
|
||||
return if root.nil?
|
||||
|
||||
[class]{}-[func]{inOrder}
|
||||
|
||||
[class]{}-[func]{postOrder}
|
||||
# Visit priority: left subtree -> right subtree -> root node
|
||||
post_order(root.left)
|
||||
post_order(root.right)
|
||||
$res << root.val
|
||||
end
|
||||
```
|
||||
|
||||
!!! tip
|
||||
|
||||
Depth-first search can also be implemented based on iteration, interested readers can study this on their own.
|
||||
|
||||
Figure 7-11 shows the recursive process of pre-order traversal of a binary tree, which can be divided into two opposite parts: "recursion" and "return".
|
||||
Figure 7-11 shows the recursive process of preorder traversal of a binary tree, which can be divided into two opposite parts: "recursion" and "return".
|
||||
|
||||
1. "Recursion" means starting a new method, the program accesses the next node in this process.
|
||||
2. "Return" means the function returns, indicating the current node has been fully accessed.
|
||||
1. "Recursion" means opening a new method, where the program accesses the next node in this process.
|
||||
2. "Return" means the function returns, indicating that the current node has been fully visited.
|
||||
|
||||
=== "<1>"
|
||||
{ class="animation-figure" }
|
||||
{ class="animation-figure" }
|
||||
|
||||
=== "<2>"
|
||||
{ class="animation-figure" }
|
||||
@@ -423,9 +856,9 @@ Figure 7-11 shows the recursive process of pre-order traversal of a binary tree,
|
||||
=== "<11>"
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 7-11 The recursive process of pre-order traversal </p>
|
||||
<p align="center"> Figure 7-11 The recursive process of preorder traversal </p>
|
||||
|
||||
### 2. Complexity analysis
|
||||
### 2. Complexity Analysis
|
||||
|
||||
- **Time complexity is $O(n)$**: All nodes are visited once, using $O(n)$ time.
|
||||
- **Space complexity is $O(n)$**: In the worst case, i.e., the tree degenerates into a linked list, the recursion depth reaches $n$, the system occupies $O(n)$ stack frame space.
|
||||
- **Space complexity is $O(n)$**: In the worst case, i.e., the tree degenerates into a linked list, the recursion depth reaches $n$, and the system occupies $O(n)$ stack frame space.
|
||||
|
||||
Reference in New Issue
Block a user