translation: Add the initial translation for the tree chapter (#1208)
* Add the initial translation for the tree chapter * Add intial translation of array_representation_of_tree.md * Fix the code link of avl_treepull/1209/head
After Width: | Height: | Size: 27 KiB |
After Width: | Height: | Size: 19 KiB |
After Width: | Height: | Size: 22 KiB |
After Width: | Height: | Size: 19 KiB |
@ -0,0 +1,164 @@
|
|||||||
|
# Array representation of binary trees
|
||||||
|
|
||||||
|
Under the linked list representation, the storage unit of a binary tree is a node `TreeNode`, with nodes connected by pointers. The basic operations of binary trees under the linked list representation were introduced in the previous section.
|
||||||
|
|
||||||
|
So, can we use an array to represent a binary tree? The answer is yes.
|
||||||
|
|
||||||
|
## Representing perfect binary trees
|
||||||
|
|
||||||
|
Let's analyze a simple case first. Given a perfect binary tree, we store all nodes in an array according to the order of level-order traversal, where each node corresponds to a unique array index.
|
||||||
|
|
||||||
|
Based on the characteristics of level-order traversal, we can deduce a "mapping formula" between the index of a parent node and its children: **If a node's index is $i$, then the index of its left child is $2i + 1$ and the right child is $2i + 2$**. The figure below shows the mapping relationship between the indices of various nodes.
|
||||||
|
|
||||||
|
![Array representation of a perfect binary tree](array_representation_of_tree.assets/array_representation_binary_tree.png)
|
||||||
|
|
||||||
|
**The mapping formula plays a role similar to the node references (pointers) in linked lists**. Given any node in the array, we can access its left (right) child node using the mapping formula.
|
||||||
|
|
||||||
|
## Representing any binary tree
|
||||||
|
|
||||||
|
Perfect binary trees are a special case; there are often many `None` values in the middle levels of a binary tree. Since the sequence of level-order traversal does not include these `None` values, we cannot solely rely on this sequence to deduce the number and distribution of `None` values. **This means that multiple binary tree structures can match the same level-order traversal sequence**.
|
||||||
|
|
||||||
|
As shown in the figure below, given a non-perfect binary tree, the above method of array representation fails.
|
||||||
|
|
||||||
|
![Level-order traversal sequence corresponds to multiple binary tree possibilities](array_representation_of_tree.assets/array_representation_without_empty.png)
|
||||||
|
|
||||||
|
To solve this problem, **we can consider explicitly writing out all `None` values in the level-order traversal sequence**. As shown in the following figure, after this treatment, the level-order traversal sequence can uniquely represent a binary tree. Example code is as follows:
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
```python title=""
|
||||||
|
# Array representation of a binary tree
|
||||||
|
# Using None to represent empty slots
|
||||||
|
tree = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C++"
|
||||||
|
|
||||||
|
```cpp title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using the maximum integer value INT_MAX to mark empty slots
|
||||||
|
vector<int> tree = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Java"
|
||||||
|
|
||||||
|
```java title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using the Integer wrapper class allows for using null to mark empty slots
|
||||||
|
Integer[] tree = { 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 };
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C#"
|
||||||
|
|
||||||
|
```csharp title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using nullable int (int?) allows for using null to mark empty slots
|
||||||
|
int?[] tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Go"
|
||||||
|
|
||||||
|
```go title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using an any type slice, allowing for nil to mark empty slots
|
||||||
|
tree := []any{1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Swift"
|
||||||
|
|
||||||
|
```swift title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using optional Int (Int?) allows for using nil to mark empty slots
|
||||||
|
let tree: [Int?] = [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "JS"
|
||||||
|
|
||||||
|
```javascript title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using null to represent empty slots
|
||||||
|
let tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "TS"
|
||||||
|
|
||||||
|
```typescript title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using null to represent empty slots
|
||||||
|
let tree: (number | null)[] = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Dart"
|
||||||
|
|
||||||
|
```dart title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using nullable int (int?) allows for using null to mark empty slots
|
||||||
|
List<int?> tree = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Rust"
|
||||||
|
|
||||||
|
```rust title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using None to mark empty slots
|
||||||
|
let tree = [Some(1), Some(2), Some(3), Some(4), None, Some(6), Some(7), Some(8), Some(9), None, None, Some(12), None, None, Some(15)];
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C"
|
||||||
|
|
||||||
|
```c title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using the maximum int value to mark empty slots, therefore, node values must not be INT_MAX
|
||||||
|
int tree[] = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Kotlin"
|
||||||
|
|
||||||
|
```kotlin title=""
|
||||||
|
/* Array representation of a binary tree */
|
||||||
|
// Using null to represent empty slots
|
||||||
|
val tree = mutableListOf( 1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15 )
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Ruby"
|
||||||
|
|
||||||
|
```ruby title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Zig"
|
||||||
|
|
||||||
|
```zig title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
![Array representation of any type of binary tree](array_representation_of_tree.assets/array_representation_with_empty.png)
|
||||||
|
|
||||||
|
It's worth noting that **complete binary trees are very suitable for array representation**. Recalling the definition of a complete binary tree, `None` appears only at the bottom level and towards the right, **meaning all `None` values definitely appear at the end of the level-order traversal sequence**.
|
||||||
|
|
||||||
|
This means that when using an array to represent a complete binary tree, it's possible to omit storing all `None` values, which is very convenient. The figure below gives an example.
|
||||||
|
|
||||||
|
![Array representation of a complete binary tree](array_representation_of_tree.assets/array_representation_complete_binary_tree.png)
|
||||||
|
|
||||||
|
The following code implements a binary tree based on array representation, including the following operations:
|
||||||
|
|
||||||
|
- Given a node, obtain its value, left (right) child node, and parent node.
|
||||||
|
- Obtain the preorder, inorder, postorder, and level-order traversal sequences.
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{array_binary_tree}-[class]{array_binary_tree}-[func]{}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advantages and limitations
|
||||||
|
|
||||||
|
The array representation of binary trees has the following advantages:
|
||||||
|
|
||||||
|
- Arrays are stored in contiguous memory spaces, which is cache-friendly and allows for faster access and traversal.
|
||||||
|
- It does not require storing pointers, which saves space.
|
||||||
|
- It allows random access to nodes.
|
||||||
|
|
||||||
|
However, the array representation also has some limitations:
|
||||||
|
|
||||||
|
- Array storage requires contiguous memory space, so it is not suitable for storing trees with a large amount of data.
|
||||||
|
- Adding or deleting nodes requires array insertion and deletion operations, which are less efficient.
|
||||||
|
- When there are many `None` values in the binary tree, the proportion of node data contained in the array is low, leading to lower space utilization.
|
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 21 KiB |
After Width: | Height: | Size: 21 KiB |
After Width: | Height: | Size: 25 KiB |
After Width: | Height: | Size: 22 KiB |
After Width: | Height: | Size: 9.8 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 17 KiB |
After Width: | Height: | Size: 22 KiB |
After Width: | Height: | Size: 25 KiB |
After Width: | Height: | Size: 22 KiB |
@ -0,0 +1,353 @@
|
|||||||
|
# AVL tree *
|
||||||
|
|
||||||
|
In the "Binary Search Tree" section, we mentioned that after multiple insertions and removals, a binary search tree might degrade to a linked list. In such cases, the time complexity of all operations degrades from $O(\log n)$ to $O(n)$.
|
||||||
|
|
||||||
|
As shown in the figure below, after two node removal operations, this binary search tree will degrade into a linked list.
|
||||||
|
|
||||||
|
![Degradation of an AVL tree after removing nodes](avl_tree.assets/avltree_degradation_from_removing_node.png)
|
||||||
|
|
||||||
|
For example, in the perfect binary tree shown in the figure below, after inserting two nodes, the tree will lean heavily to the left, and the time complexity of search operations will also degrade.
|
||||||
|
|
||||||
|
![Degradation of an AVL tree after inserting nodes](avl_tree.assets/avltree_degradation_from_inserting_node.png)
|
||||||
|
|
||||||
|
In 1962, G. M. Adelson-Velsky and E. M. Landis proposed the "AVL Tree" in their paper "An algorithm for the organization of information". The paper detailed a series of operations to ensure that after continuously adding and removing nodes, the AVL tree would not degrade, thus maintaining the time complexity of various operations at $O(\log n)$ level. In other words, in scenarios where frequent additions, removals, searches, and modifications are needed, the AVL tree can always maintain efficient data operation performance, which has great application value.
|
||||||
|
|
||||||
|
## Common terminology in AVL trees
|
||||||
|
|
||||||
|
An AVL tree is both a binary search tree and a balanced binary tree, satisfying all properties of these two types of binary trees, hence it is a "balanced binary search tree".
|
||||||
|
|
||||||
|
### Node height
|
||||||
|
|
||||||
|
Since the operations related to AVL trees require obtaining node heights, we need to add a `height` variable to the node class:
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
```python title=""
|
||||||
|
class TreeNode:
|
||||||
|
"""AVL tree node"""
|
||||||
|
def __init__(self, val: int):
|
||||||
|
self.val: int = val # Node value
|
||||||
|
self.height: int = 0 # Node height
|
||||||
|
self.left: TreeNode | None = None # Left child reference
|
||||||
|
self.right: TreeNode | None = None # Right child reference
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C++"
|
||||||
|
|
||||||
|
```cpp title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
struct TreeNode {
|
||||||
|
int val{}; // Node value
|
||||||
|
int height = 0; // Node height
|
||||||
|
TreeNode *left{}; // Left child
|
||||||
|
TreeNode *right{}; // Right child
|
||||||
|
TreeNode() = default;
|
||||||
|
explicit TreeNode(int x) : val(x){}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Java"
|
||||||
|
|
||||||
|
```java title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode {
|
||||||
|
public int val; // Node value
|
||||||
|
public int height; // Node height
|
||||||
|
public TreeNode left; // Left child
|
||||||
|
public TreeNode right; // Right child
|
||||||
|
public TreeNode(int x) { val = x; }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C#"
|
||||||
|
|
||||||
|
```csharp title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode(int? x) {
|
||||||
|
public int? val = x; // Node value
|
||||||
|
public int height; // Node height
|
||||||
|
public TreeNode? left; // Left child reference
|
||||||
|
public TreeNode? right; // Right child reference
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Go"
|
||||||
|
|
||||||
|
```go title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
type TreeNode struct {
|
||||||
|
Val int // Node value
|
||||||
|
Height int // Node height
|
||||||
|
Left *TreeNode // Left child reference
|
||||||
|
Right *TreeNode // Right child reference
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Swift"
|
||||||
|
|
||||||
|
```swift title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode {
|
||||||
|
var val: Int // Node value
|
||||||
|
var height: Int // Node height
|
||||||
|
var left: TreeNode? // Left child
|
||||||
|
var right: TreeNode? // Right child
|
||||||
|
|
||||||
|
init(x: Int) {
|
||||||
|
val = x
|
||||||
|
height = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "JS"
|
||||||
|
|
||||||
|
```javascript title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode {
|
||||||
|
val; // Node value
|
||||||
|
height; // Node height
|
||||||
|
left; // Left child pointer
|
||||||
|
right; // Right child pointer
|
||||||
|
constructor(val, left, right, height) {
|
||||||
|
this.val = val === undefined ? 0 : val;
|
||||||
|
this.height = height === undefined ? 0 : height;
|
||||||
|
this.left = left === undefined ? null : left;
|
||||||
|
this.right = right === undefined ? null : right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "TS"
|
||||||
|
|
||||||
|
```typescript title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode {
|
||||||
|
val: number; // Node value
|
||||||
|
height: number; // Node height
|
||||||
|
left: TreeNode | null; // Left child pointer
|
||||||
|
right: TreeNode | null; // Right child pointer
|
||||||
|
constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) {
|
||||||
|
this.val = val === undefined ? 0 : val;
|
||||||
|
this.height = height === undefined ? 0 : height;
|
||||||
|
this.left = left === undefined ? null : left;
|
||||||
|
this.right = right === undefined ? null : right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Dart"
|
||||||
|
|
||||||
|
```dart title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode {
|
||||||
|
int val; // Node value
|
||||||
|
int height; // Node height
|
||||||
|
TreeNode? left; // Left child
|
||||||
|
TreeNode? right; // Right child
|
||||||
|
TreeNode(this.val, [this.height = 0, this.left, this.right]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Rust"
|
||||||
|
|
||||||
|
```rust title=""
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
|
/* AVL tree node */
|
||||||
|
struct TreeNode {
|
||||||
|
val: i32, // Node value
|
||||||
|
height: i32, // Node height
|
||||||
|
left: Option<Rc<RefCell<TreeNode>>>, // Left child
|
||||||
|
right: Option<Rc<RefCell<TreeNode>>>, // Right child
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TreeNode {
|
||||||
|
/* Constructor */
|
||||||
|
fn new(val: i32) -> Rc<RefCell<Self>> {
|
||||||
|
Rc::new(RefCell::new(Self {
|
||||||
|
val,
|
||||||
|
height: 0,
|
||||||
|
left: None,
|
||||||
|
right: None
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C"
|
||||||
|
|
||||||
|
```c title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
TreeNode struct TreeNode {
|
||||||
|
int val;
|
||||||
|
int height;
|
||||||
|
struct TreeNode *left;
|
||||||
|
struct TreeNode *right;
|
||||||
|
} TreeNode;
|
||||||
|
|
||||||
|
/* Constructor */
|
||||||
|
TreeNode *newTreeNode(int val) {
|
||||||
|
TreeNode *node;
|
||||||
|
|
||||||
|
node = (TreeNode *)malloc(sizeof(TreeNode));
|
||||||
|
node->val = val;
|
||||||
|
node->height = 0;
|
||||||
|
node->left = NULL;
|
||||||
|
node->right = NULL;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Kotlin"
|
||||||
|
|
||||||
|
```kotlin title=""
|
||||||
|
/* AVL tree node */
|
||||||
|
class TreeNode(val _val: Int) { // Node value
|
||||||
|
val height: Int = 0 // Node height
|
||||||
|
val left: TreeNode? = null // Left child
|
||||||
|
val right: TreeNode? = null // Right child
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Ruby"
|
||||||
|
|
||||||
|
```ruby title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Zig"
|
||||||
|
|
||||||
|
```zig title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
The "node height" refers to the distance from that node to its farthest leaf node, i.e., the number of "edges" passed. It is important to note that the height of a leaf node is $0$, and the height of a null node is $-1$. We will create two utility functions for getting and updating the height of a node:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{update_height}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Node balance factor
|
||||||
|
|
||||||
|
The "balance factor" of a node is defined as the height of the node's left subtree minus the height of its right subtree, with the balance factor of a null node defined as $0$. We will also encapsulate the functionality of obtaining the node balance factor into a function for easy use later on:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{balance_factor}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
|
||||||
|
Let the balance factor be $f$, then the balance factor of any node in an AVL tree satisfies $-1 \le f \le 1$.
|
||||||
|
|
||||||
|
## Rotations in AVL trees
|
||||||
|
|
||||||
|
The characteristic feature of an AVL tree is the "rotation" operation, which can restore balance to an unbalanced node without affecting the in-order traversal sequence of the binary tree. In other words, **the rotation operation can maintain the property of a "binary search tree" while also turning the tree back into a "balanced binary tree"**.
|
||||||
|
|
||||||
|
We call nodes with an absolute balance factor $> 1$ "unbalanced nodes". Depending on the type of imbalance, there are four kinds of rotations: right rotation, left rotation, right-left rotation, and left-right rotation. Below, we detail these rotation operations.
|
||||||
|
|
||||||
|
### Right rotation
|
||||||
|
|
||||||
|
As shown in the figure below, the first unbalanced node from the bottom up in the binary tree is "node 3". Focusing on the subtree with this unbalanced node as the root, denoted as `node`, and its left child as `child`, perform a "right rotation". After the right rotation, the subtree is balanced again while still maintaining the properties of a binary search tree.
|
||||||
|
|
||||||
|
=== "<1>"
|
||||||
|
![Steps of right rotation](avl_tree.assets/avltree_right_rotate_step1.png)
|
||||||
|
|
||||||
|
=== "<2>"
|
||||||
|
![avltree_right_rotate_step2](avl_tree.assets/avltree_right_rotate_step2.png)
|
||||||
|
|
||||||
|
=== "<3>"
|
||||||
|
![avltree_right_rotate_step3](avl_tree.assets/avltree_right_rotate_step3.png)
|
||||||
|
|
||||||
|
=== "<4>"
|
||||||
|
![avltree_right_rotate_step4](avl_tree.assets/avltree_right_rotate_step4.png)
|
||||||
|
|
||||||
|
As shown in the figure below, when the `child` node has a right child (denoted as `grand_child`), a step needs to be added in the right rotation: set `grand_child` as the left child of `node`.
|
||||||
|
|
||||||
|
![Right rotation with grand_child](avl_tree.assets/avltree_right_rotate_with_grandchild.png)
|
||||||
|
|
||||||
|
"Right rotation" is a figurative term; in practice, it is achieved by modifying node pointers, as shown in the following code:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{right_rotate}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Left rotation
|
||||||
|
|
||||||
|
Correspondingly, if considering the "mirror" of the above unbalanced binary tree, the "left rotation" operation shown in the figure below needs to be performed.
|
||||||
|
|
||||||
|
![Left rotation operation](avl_tree.assets/avltree_left_rotate.png)
|
||||||
|
|
||||||
|
Similarly, as shown in the figure below, when the `child` node has a left child (denoted as `grand_child`), a step needs to be added in the left rotation: set `grand_child` as the right child of `node`.
|
||||||
|
|
||||||
|
![Left rotation with grand_child](avl_tree.assets/avltree_left_rotate_with_grandchild.png)
|
||||||
|
|
||||||
|
It can be observed that **the right and left rotation operations are logically symmetrical, and they solve two symmetrical types of imbalance**. Based on symmetry, by replacing all `left` with `right`, and all `right` with `left` in the implementation code of right rotation, we can get the implementation code for left rotation:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{left_rotate}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Right-left rotation
|
||||||
|
|
||||||
|
For the unbalanced node 3 shown in the figure below, using either left or right rotation alone cannot restore balance to the subtree. In this case, a "left rotation" needs to be performed on `child` first, followed by a "right rotation" on `node`.
|
||||||
|
|
||||||
|
![Right-left rotation](avl_tree.assets/avltree_left_right_rotate.png)
|
||||||
|
|
||||||
|
### Left-right rotation
|
||||||
|
|
||||||
|
As shown in the figure below, for the mirror case of the above unbalanced binary tree, a "right rotation" needs to be performed on `child` first, followed by a "left rotation" on `node`.
|
||||||
|
|
||||||
|
![Left-right rotation](avl_tree.assets/avltree_right_left_rotate.png)
|
||||||
|
|
||||||
|
### Choice of rotation
|
||||||
|
|
||||||
|
The four kinds of imbalances shown in the figure below correspond to the cases described above, respectively requiring right rotation, left-right rotation, right-left rotation, and left rotation.
|
||||||
|
|
||||||
|
![The four rotation cases of AVL tree](avl_tree.assets/avltree_rotation_cases.png)
|
||||||
|
|
||||||
|
As shown in the table below, we determine which of the above cases an unbalanced node belongs to by judging the sign of the balance factor of the unbalanced node and its higher-side child's balance factor.
|
||||||
|
|
||||||
|
<p align="center"> Table <id> Conditions for Choosing Among the Four Rotation Cases </p>
|
||||||
|
|
||||||
|
| Balance factor of unbalanced node | Balance factor of child node | Rotation method to use |
|
||||||
|
| --------------------------------- | ---------------------------- | --------------------------------- |
|
||||||
|
| $> 1$ (Left-leaning tree) | $\geq 0$ | Right rotation |
|
||||||
|
| $> 1$ (Left-leaning tree) | $<0$ | Left rotation then right rotation |
|
||||||
|
| $< -1$ (Right-leaning tree) | $\leq 0$ | Left rotation |
|
||||||
|
| $< -1$ (Right-leaning tree) | $>0$ | Right rotation then left rotation |
|
||||||
|
|
||||||
|
For convenience, we encapsulate the rotation operations into a function. **With this function, we can perform rotations on various kinds of imbalances, restoring balance to unbalanced nodes**. The code is as follows:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{rotate}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common operations in AVL trees
|
||||||
|
|
||||||
|
### Node insertion
|
||||||
|
|
||||||
|
The node insertion operation in AVL trees is similar to that in binary search trees. The only difference is that after inserting a node in an AVL tree, a series of unbalanced nodes may appear along the path from that node to the root node. Therefore, **we need to start from this node and perform rotation operations upwards to restore balance to all unbalanced nodes**. The code is as follows:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{insert_helper}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Node removal
|
||||||
|
|
||||||
|
Similarly, based on the method of removing nodes in binary search trees, rotation operations need to be performed from the bottom up to restore balance to all unbalanced nodes. The code is as follows:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{avl_tree}-[class]{avl_tree}-[func]{remove_helper}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Node search
|
||||||
|
|
||||||
|
The node search operation in AVL trees is consistent with that in binary search trees and will not be detailed here.
|
||||||
|
|
||||||
|
## Typical applications of AVL trees
|
||||||
|
|
||||||
|
- Organizing and storing large amounts of data, suitable for scenarios with high-frequency searches and low-frequency intertions and removals.
|
||||||
|
- Used to build index systems in databases.
|
||||||
|
- Red-black trees are also a common type of balanced binary search tree. Compared to AVL trees, red-black trees have more relaxed balancing conditions, require fewer rotations for node insertion and removal, and have a higher average efficiency for node addition and removal operations.
|
After Width: | Height: | Size: 12 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 30 KiB |
After Width: | Height: | Size: 25 KiB |
After Width: | Height: | Size: 28 KiB |
After Width: | Height: | Size: 26 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 26 KiB |
After Width: | Height: | Size: 27 KiB |
After Width: | Height: | Size: 29 KiB |
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 16 KiB |
@ -0,0 +1,129 @@
|
|||||||
|
# Binary search tree
|
||||||
|
|
||||||
|
As shown in the figure below, a "binary search tree" satisfies the following conditions.
|
||||||
|
|
||||||
|
1. For the root node, the value of all nodes in the left subtree < the value of the root node < the value of all nodes in the right subtree.
|
||||||
|
2. The left and right subtrees of any node are also binary search trees, i.e., they satisfy condition `1.` as well.
|
||||||
|
|
||||||
|
![Binary search tree](binary_search_tree.assets/binary_search_tree.png)
|
||||||
|
|
||||||
|
## Operations on a binary search tree
|
||||||
|
|
||||||
|
We encapsulate the binary search tree as a class `BinarySearchTree` and declare a member variable `root`, pointing to the tree's root node.
|
||||||
|
|
||||||
|
### Searching for a node
|
||||||
|
|
||||||
|
Given a target node value `num`, one can search according to the properties of the binary search tree. As shown in the figure below, we declare a node `cur` and start from the binary tree's root node `root`, looping to compare the size relationship between the node value `cur.val` and `num`.
|
||||||
|
|
||||||
|
- If `cur.val < num`, it means the target node is in `cur`'s right subtree, thus execute `cur = cur.right`.
|
||||||
|
- If `cur.val > num`, it means the target node is in `cur`'s left subtree, thus execute `cur = cur.left`.
|
||||||
|
- If `cur.val = num`, it means the target node is found, exit the loop and return the node.
|
||||||
|
|
||||||
|
=== "<1>"
|
||||||
|
![Example of searching for a node in a binary search tree](binary_search_tree.assets/bst_search_step1.png)
|
||||||
|
|
||||||
|
=== "<2>"
|
||||||
|
![bst_search_step2](binary_search_tree.assets/bst_search_step2.png)
|
||||||
|
|
||||||
|
=== "<3>"
|
||||||
|
![bst_search_step3](binary_search_tree.assets/bst_search_step3.png)
|
||||||
|
|
||||||
|
=== "<4>"
|
||||||
|
![bst_search_step4](binary_search_tree.assets/bst_search_step4.png)
|
||||||
|
|
||||||
|
The search operation in a binary search tree works on the same principle as the binary search algorithm, eliminating half of the possibilities in each round. The number of loops is at most the height of the binary tree. When the binary tree is balanced, it uses $O(\log n)$ time. Example code is as follows:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{search}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Inserting a node
|
||||||
|
|
||||||
|
Given an element `num` to be inserted, to maintain the property of the binary search tree "left subtree < root node < right subtree," the insertion operation proceeds as shown in the figure below.
|
||||||
|
|
||||||
|
1. **Finding the insertion position**: Similar to the search operation, start from the root node and loop downwards according to the size relationship between the current node value and `num` until passing through the leaf node (traversing to `None`) then exit the loop.
|
||||||
|
2. **Insert the node at that position**: Initialize the node `num` and place it where `None` was.
|
||||||
|
|
||||||
|
![Inserting a node into a binary search tree](binary_search_tree.assets/bst_insert.png)
|
||||||
|
|
||||||
|
In the code implementation, note the following two points.
|
||||||
|
|
||||||
|
- The binary search tree does not allow duplicate nodes; otherwise, it will violate its definition. Therefore, if the node to be inserted already exists in the tree, the insertion is not performed, and it directly returns.
|
||||||
|
- To perform the insertion operation, we need to use the node `pre` to save the node from the last loop. This way, when traversing to `None`, we can get its parent node, thus completing the node insertion operation.
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{insert}
|
||||||
|
```
|
||||||
|
|
||||||
|
Similar to searching for a node, inserting a node uses $O(\log n)$ time.
|
||||||
|
|
||||||
|
### Removing a node
|
||||||
|
|
||||||
|
First, find the target node in the binary tree, then remove it. Similar to inserting a node, we need to ensure that after the removal operation is completed, the property of the binary search tree "left subtree < root node < right subtree" is still satisfied. Therefore, based on the number of child nodes of the target node, we divide it into 0, 1, and 2 cases, performing the corresponding node removal operations.
|
||||||
|
|
||||||
|
As shown in the figure below, when the degree of the node to be removed is $0$, it means the node is a leaf node, and it can be directly removed.
|
||||||
|
|
||||||
|
![Removing a node in a binary search tree (degree 0)](binary_search_tree.assets/bst_remove_case1.png)
|
||||||
|
|
||||||
|
As shown in the figure below, when the degree of the node to be removed is $1$, replacing the node to be removed with its child node is sufficient.
|
||||||
|
|
||||||
|
![Removing a node in a binary search tree (degree 1)](binary_search_tree.assets/bst_remove_case2.png)
|
||||||
|
|
||||||
|
When the degree of the node to be removed is $2$, we cannot remove it directly, but need to use a node to replace it. To maintain the property of the binary search tree "left subtree < root node < right subtree," **this node can be either the smallest node of the right subtree or the largest node of the left subtree**.
|
||||||
|
|
||||||
|
Assuming we choose the smallest node of the right subtree (the next node in in-order traversal), then the removal operation proceeds as shown in the figure below.
|
||||||
|
|
||||||
|
1. Find the next node in the "in-order traversal sequence" of the node to be removed, denoted as `tmp`.
|
||||||
|
2. Replace the value of the node to be removed with `tmp`'s value, and recursively remove the node `tmp` in the tree.
|
||||||
|
|
||||||
|
=== "<1>"
|
||||||
|
![Removing a node in a binary search tree (degree 2)](binary_search_tree.assets/bst_remove_case3_step1.png)
|
||||||
|
|
||||||
|
=== "<2>"
|
||||||
|
![bst_remove_case3_step2](binary_search_tree.assets/bst_remove_case3_step2.png)
|
||||||
|
|
||||||
|
=== "<3>"
|
||||||
|
![bst_remove_case3_step3](binary_search_tree.assets/bst_remove_case3_step3.png)
|
||||||
|
|
||||||
|
=== "<4>"
|
||||||
|
![bst_remove_case3_step4](binary_search_tree.assets/bst_remove_case3_step4.png)
|
||||||
|
|
||||||
|
The operation of removing a node also uses $O(\log n)$ time, where finding the node to be removed requires $O(\log n)$ time, and obtaining the in-order traversal successor node requires $O(\log n)$ time. Example code is as follows:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{binary_search_tree}-[class]{binary_search_tree}-[func]{remove}
|
||||||
|
```
|
||||||
|
|
||||||
|
### In-order traversal is ordered
|
||||||
|
|
||||||
|
As shown in the figure below, the in-order traversal of a binary tree follows the "left $\rightarrow$ root $\rightarrow$ right" traversal order, and a binary search tree satisfies the size relationship "left child node < root node < right child node".
|
||||||
|
|
||||||
|
This means that in-order traversal in a binary search tree always traverses the next smallest node first, thus deriving an important property: **The in-order traversal sequence of a binary search tree is ascending**.
|
||||||
|
|
||||||
|
Using the ascending property of in-order traversal, obtaining ordered data in a binary search tree requires only $O(n)$ time, without the need for additional sorting operations, which is very efficient.
|
||||||
|
|
||||||
|
![In-order traversal sequence of a binary search tree](binary_search_tree.assets/bst_inorder_traversal.png)
|
||||||
|
|
||||||
|
## Efficiency of binary search trees
|
||||||
|
|
||||||
|
Given a set of data, we consider using an array or a binary search tree for storage. Observing the table below, the operations on a binary search tree all have logarithmic time complexity, which is stable and efficient. Only in scenarios of high-frequency addition and low-frequency search and removal, arrays are more efficient than binary search trees.
|
||||||
|
|
||||||
|
<p align="center"> Table <id> Efficiency comparison between arrays and search trees </p>
|
||||||
|
|
||||||
|
| | Unsorted array | Binary search tree |
|
||||||
|
| -------------- | -------------- | ------------------ |
|
||||||
|
| Search element | $O(n)$ | $O(\log n)$ |
|
||||||
|
| Insert element | $O(1)$ | $O(\log n)$ |
|
||||||
|
| Remove element | $O(n)$ | $O(\log n)$ |
|
||||||
|
|
||||||
|
In ideal conditions, the binary search tree is "balanced," thus any node can be found within $\log n$ loops.
|
||||||
|
|
||||||
|
However, continuously inserting and removing nodes in a binary search tree may lead to the binary tree degenerating into a chain list as shown in the figure below, at which point the time complexity of various operations also degrades to $O(n)$.
|
||||||
|
|
||||||
|
![Degradation of a binary search tree](binary_search_tree.assets/bst_degradation.png)
|
||||||
|
|
||||||
|
## Common applications of binary search trees
|
||||||
|
|
||||||
|
- Used as multi-level indexes in systems to implement efficient search, insertion, and removal operations.
|
||||||
|
- Serves as the underlying data structure for certain search algorithms.
|
||||||
|
- Used to store data streams to maintain their ordered state.
|
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 20 KiB |
After Width: | Height: | Size: 17 KiB |
After Width: | Height: | Size: 24 KiB |
After Width: | Height: | Size: 20 KiB |
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 15 KiB |
@ -0,0 +1,662 @@
|
|||||||
|
# Binary tree
|
||||||
|
|
||||||
|
A "binary tree" is a non-linear data structure that represents the ancestral and descendent relationships, embodying the "divide and conquer" logic. Similar to a linked list, the basic unit of a binary tree is a node, each containing a value, a reference to the left child node, and a reference to the right child node.
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
```python title=""
|
||||||
|
class TreeNode:
|
||||||
|
"""Binary tree node"""
|
||||||
|
def __init__(self, val: int):
|
||||||
|
self.val: int = val # Node value
|
||||||
|
self.left: TreeNode | None = None # Reference to left child node
|
||||||
|
self.right: TreeNode | None = None # Reference to right child node
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C++"
|
||||||
|
|
||||||
|
```cpp title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
struct TreeNode {
|
||||||
|
int val; // Node value
|
||||||
|
TreeNode *left; // Pointer to left child node
|
||||||
|
TreeNode *right; // Pointer to right child node
|
||||||
|
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Java"
|
||||||
|
|
||||||
|
```java title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode {
|
||||||
|
int val; // Node value
|
||||||
|
TreeNode left; // Reference to left child node
|
||||||
|
TreeNode right; // Reference to right child node
|
||||||
|
TreeNode(int x) { val = x; }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C#"
|
||||||
|
|
||||||
|
```csharp title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode(int? x) {
|
||||||
|
public int? val = x; // Node value
|
||||||
|
public TreeNode? left; // Reference to left child node
|
||||||
|
public TreeNode? right; // Reference to right child node
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Go"
|
||||||
|
|
||||||
|
```go title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
type TreeNode struct {
|
||||||
|
Val int
|
||||||
|
Left *TreeNode
|
||||||
|
Right *TreeNode
|
||||||
|
}
|
||||||
|
/* 构造方法 */
|
||||||
|
func NewTreeNode(v int) *TreeNode {
|
||||||
|
return &TreeNode{
|
||||||
|
Left: nil, // Pointer to left child node
|
||||||
|
Right: nil, // Pointer to right child node
|
||||||
|
Val: v, // Node value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Swift"
|
||||||
|
|
||||||
|
```swift title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode {
|
||||||
|
var val: Int // Node value
|
||||||
|
var left: TreeNode? // Reference to left child node
|
||||||
|
var right: TreeNode? // Reference to right child node
|
||||||
|
|
||||||
|
init(x: Int) {
|
||||||
|
val = x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "JS"
|
||||||
|
|
||||||
|
```javascript title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode {
|
||||||
|
val; // Node value
|
||||||
|
left; // Pointer to left child node
|
||||||
|
right; // Pointer to right child node
|
||||||
|
constructor(val, left, right) {
|
||||||
|
this.val = val === undefined ? 0 : val;
|
||||||
|
this.left = left === undefined ? null : left;
|
||||||
|
this.right = right === undefined ? null : right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "TS"
|
||||||
|
|
||||||
|
```typescript title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode {
|
||||||
|
val: number;
|
||||||
|
left: TreeNode | null;
|
||||||
|
right: TreeNode | null;
|
||||||
|
|
||||||
|
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
|
||||||
|
this.val = val === undefined ? 0 : val; // Node value
|
||||||
|
this.left = left === undefined ? null : left; // Reference to left child node
|
||||||
|
this.right = right === undefined ? null : right; // Reference to right child node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Dart"
|
||||||
|
|
||||||
|
```dart title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode {
|
||||||
|
int val; // Node value
|
||||||
|
TreeNode? left; // Reference to left child node
|
||||||
|
TreeNode? right; // Reference to right child node
|
||||||
|
TreeNode(this.val, [this.left, this.right]);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Rust"
|
||||||
|
|
||||||
|
```rust title=""
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
|
||||||
|
/* Binary tree node */
|
||||||
|
struct TreeNode {
|
||||||
|
val: i32, // Node value
|
||||||
|
left: Option<Rc<RefCell<TreeNode>>>, // Reference to left child node
|
||||||
|
right: Option<Rc<RefCell<TreeNode>>>, // Reference to right child node
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TreeNode {
|
||||||
|
/* 构造方法 */
|
||||||
|
fn new(val: i32) -> Rc<RefCell<Self>> {
|
||||||
|
Rc::new(RefCell::new(Self {
|
||||||
|
val,
|
||||||
|
left: None,
|
||||||
|
right: None
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C"
|
||||||
|
|
||||||
|
```c title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
typedef struct TreeNode {
|
||||||
|
int val; // Node value
|
||||||
|
int height; // 节点高度
|
||||||
|
struct TreeNode *left; // Pointer to left child node
|
||||||
|
struct TreeNode *right; // Pointer to right child node
|
||||||
|
} TreeNode;
|
||||||
|
|
||||||
|
/* 构造函数 */
|
||||||
|
TreeNode *newTreeNode(int val) {
|
||||||
|
TreeNode *node;
|
||||||
|
|
||||||
|
node = (TreeNode *)malloc(sizeof(TreeNode));
|
||||||
|
node->val = val;
|
||||||
|
node->height = 0;
|
||||||
|
node->left = NULL;
|
||||||
|
node->right = NULL;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Kotlin"
|
||||||
|
|
||||||
|
```kotlin title=""
|
||||||
|
/* Binary tree node */
|
||||||
|
class TreeNode(val _val: Int) { // Node value
|
||||||
|
val left: TreeNode? = null // Reference to left child node
|
||||||
|
val right: TreeNode? = null // Reference to right child node
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Ruby"
|
||||||
|
|
||||||
|
```ruby title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Zig"
|
||||||
|
|
||||||
|
```zig title=""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Each node has two references (pointers), pointing to the "left-child node" and "right-child node," respectively. This node is called the "parent node" of these two child nodes. When given a node of a binary tree, we call the tree formed by this node's left child and all nodes under it the "left subtree" of this node. Similarly, the "right subtree" can be defined.
|
||||||
|
|
||||||
|
**In a binary tree, except for leaf nodes, all other nodes contain child nodes and non-empty subtrees.** As shown in the figure below, if "Node 2" is considered as the parent node, then its left and right child nodes are "Node 4" and "Node 5," respectively. The left subtree is "the tree formed by Node 4 and all nodes under it," and the right subtree is "the tree formed by Node 5 and all nodes under it."
|
||||||
|
|
||||||
|
![Parent Node, child Node, subtree](binary_tree.assets/binary_tree_definition.png)
|
||||||
|
|
||||||
|
## Common terminology of binary trees
|
||||||
|
|
||||||
|
The commonly used terminology of binary trees is shown in the following figure.
|
||||||
|
|
||||||
|
- "Root node": The node at the top level of the binary tree, which has no parent node.
|
||||||
|
- "Leaf node": A node with no children, both of its pointers point to `None`.
|
||||||
|
- "Edge": The line segment connecting two nodes, i.e., node reference (pointer).
|
||||||
|
- The "level" of a node: Incrementing from top to bottom, with the root node's level being 1.
|
||||||
|
- The "degree" of a node: The number of a node's children. In a binary tree, the degree can be 0, 1, or 2.
|
||||||
|
- The "height" of a binary tree: The number of edges passed from the root node to the farthest leaf node.
|
||||||
|
- The "depth" of a node: The number of edges passed from the root node to the node.
|
||||||
|
- The "height" of a node: The number of edges from the farthest leaf node to the node.
|
||||||
|
|
||||||
|
![Common Terminology of Binary Trees](binary_tree.assets/binary_tree_terminology.png)
|
||||||
|
|
||||||
|
!!! tip
|
||||||
|
|
||||||
|
Please note that we usually define "height" and "depth" as "the number of edges passed," but some problems or textbooks may define them as "the number of nodes passed." In this case, both height and depth need to be incremented by 1.
|
||||||
|
|
||||||
|
## Basic operations of binary trees
|
||||||
|
|
||||||
|
### Initializing a binary tree
|
||||||
|
|
||||||
|
Similar to a linked list, initialize nodes first, then construct references (pointers).
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
```python title="binary_tree.py"
|
||||||
|
# Initializing a binary tree
|
||||||
|
# Initializing nodes
|
||||||
|
n1 = TreeNode(val=1)
|
||||||
|
n2 = TreeNode(val=2)
|
||||||
|
n3 = TreeNode(val=3)
|
||||||
|
n4 = TreeNode(val=4)
|
||||||
|
n5 = TreeNode(val=5)
|
||||||
|
# Linking references (pointers) between nodes
|
||||||
|
n1.left = n2
|
||||||
|
n1.right = n3
|
||||||
|
n2.left = n4
|
||||||
|
n2.right = n5
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C++"
|
||||||
|
|
||||||
|
```cpp title="binary_tree.cpp"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
TreeNode* n1 = new TreeNode(1);
|
||||||
|
TreeNode* n2 = new TreeNode(2);
|
||||||
|
TreeNode* n3 = new TreeNode(3);
|
||||||
|
TreeNode* n4 = new TreeNode(4);
|
||||||
|
TreeNode* n5 = new TreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1->left = n2;
|
||||||
|
n1->right = n3;
|
||||||
|
n2->left = n4;
|
||||||
|
n2->right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Java"
|
||||||
|
|
||||||
|
```java title="binary_tree.java"
|
||||||
|
// Initializing nodes
|
||||||
|
TreeNode n1 = new TreeNode(1);
|
||||||
|
TreeNode n2 = new TreeNode(2);
|
||||||
|
TreeNode n3 = new TreeNode(3);
|
||||||
|
TreeNode n4 = new TreeNode(4);
|
||||||
|
TreeNode n5 = new TreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2;
|
||||||
|
n1.right = n3;
|
||||||
|
n2.left = n4;
|
||||||
|
n2.right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C#"
|
||||||
|
|
||||||
|
```csharp title="binary_tree.cs"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
TreeNode n1 = new(1);
|
||||||
|
TreeNode n2 = new(2);
|
||||||
|
TreeNode n3 = new(3);
|
||||||
|
TreeNode n4 = new(4);
|
||||||
|
TreeNode n5 = new(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2;
|
||||||
|
n1.right = n3;
|
||||||
|
n2.left = n4;
|
||||||
|
n2.right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Go"
|
||||||
|
|
||||||
|
```go title="binary_tree.go"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
n1 := NewTreeNode(1)
|
||||||
|
n2 := NewTreeNode(2)
|
||||||
|
n3 := NewTreeNode(3)
|
||||||
|
n4 := NewTreeNode(4)
|
||||||
|
n5 := NewTreeNode(5)
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.Left = n2
|
||||||
|
n1.Right = n3
|
||||||
|
n2.Left = n4
|
||||||
|
n2.Right = n5
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Swift"
|
||||||
|
|
||||||
|
```swift title="binary_tree.swift"
|
||||||
|
// Initializing nodes
|
||||||
|
let n1 = TreeNode(x: 1)
|
||||||
|
let n2 = TreeNode(x: 2)
|
||||||
|
let n3 = TreeNode(x: 3)
|
||||||
|
let n4 = TreeNode(x: 4)
|
||||||
|
let n5 = TreeNode(x: 5)
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2
|
||||||
|
n1.right = n3
|
||||||
|
n2.left = n4
|
||||||
|
n2.right = n5
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "JS"
|
||||||
|
|
||||||
|
```javascript title="binary_tree.js"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
let n1 = new TreeNode(1),
|
||||||
|
n2 = new TreeNode(2),
|
||||||
|
n3 = new TreeNode(3),
|
||||||
|
n4 = new TreeNode(4),
|
||||||
|
n5 = new TreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2;
|
||||||
|
n1.right = n3;
|
||||||
|
n2.left = n4;
|
||||||
|
n2.right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "TS"
|
||||||
|
|
||||||
|
```typescript title="binary_tree.ts"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
let n1 = new TreeNode(1),
|
||||||
|
n2 = new TreeNode(2),
|
||||||
|
n3 = new TreeNode(3),
|
||||||
|
n4 = new TreeNode(4),
|
||||||
|
n5 = new TreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2;
|
||||||
|
n1.right = n3;
|
||||||
|
n2.left = n4;
|
||||||
|
n2.right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Dart"
|
||||||
|
|
||||||
|
```dart title="binary_tree.dart"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
TreeNode n1 = new TreeNode(1);
|
||||||
|
TreeNode n2 = new TreeNode(2);
|
||||||
|
TreeNode n3 = new TreeNode(3);
|
||||||
|
TreeNode n4 = new TreeNode(4);
|
||||||
|
TreeNode n5 = new TreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2;
|
||||||
|
n1.right = n3;
|
||||||
|
n2.left = n4;
|
||||||
|
n2.right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Rust"
|
||||||
|
|
||||||
|
```rust title="binary_tree.rs"
|
||||||
|
// Initializing nodes
|
||||||
|
let n1 = TreeNode::new(1);
|
||||||
|
let n2 = TreeNode::new(2);
|
||||||
|
let n3 = TreeNode::new(3);
|
||||||
|
let n4 = TreeNode::new(4);
|
||||||
|
let n5 = TreeNode::new(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.borrow_mut().left = Some(n2.clone());
|
||||||
|
n1.borrow_mut().right = Some(n3);
|
||||||
|
n2.borrow_mut().left = Some(n4);
|
||||||
|
n2.borrow_mut().right = Some(n5);
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C"
|
||||||
|
|
||||||
|
```c title="binary_tree.c"
|
||||||
|
/* Initializing a binary tree */
|
||||||
|
// Initializing nodes
|
||||||
|
TreeNode *n1 = newTreeNode(1);
|
||||||
|
TreeNode *n2 = newTreeNode(2);
|
||||||
|
TreeNode *n3 = newTreeNode(3);
|
||||||
|
TreeNode *n4 = newTreeNode(4);
|
||||||
|
TreeNode *n5 = newTreeNode(5);
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1->left = n2;
|
||||||
|
n1->right = n3;
|
||||||
|
n2->left = n4;
|
||||||
|
n2->right = n5;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Kotlin"
|
||||||
|
|
||||||
|
```kotlin title="binary_tree.kt"
|
||||||
|
// Initializing nodes
|
||||||
|
val n1 = TreeNode(1)
|
||||||
|
val n2 = TreeNode(2)
|
||||||
|
val n3 = TreeNode(3)
|
||||||
|
val n4 = TreeNode(4)
|
||||||
|
val n5 = TreeNode(5)
|
||||||
|
// Linking references (pointers) between nodes
|
||||||
|
n1.left = n2
|
||||||
|
n1.right = n3
|
||||||
|
n2.left = n4
|
||||||
|
n2.right = n5
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Ruby"
|
||||||
|
|
||||||
|
```ruby title="binary_tree.rb"
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Zig"
|
||||||
|
|
||||||
|
```zig title="binary_tree.zig"
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
??? pythontutor "Code visualization"
|
||||||
|
|
||||||
|
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
|
||||||
|
|
||||||
|
### Inserting and removing nodes
|
||||||
|
|
||||||
|
Similar to a linked list, inserting and removing nodes in a binary tree can be achieved by modifying pointers. The figure below provides an example.
|
||||||
|
|
||||||
|
![Inserting and removing nodes in a binary tree](binary_tree.assets/binary_tree_add_remove.png)
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
```python title="binary_tree.py"
|
||||||
|
# Inserting and removing nodes
|
||||||
|
p = TreeNode(0)
|
||||||
|
# Inserting node P between n1 -> n2
|
||||||
|
n1.left = p
|
||||||
|
p.left = n2
|
||||||
|
# Removing node P
|
||||||
|
n1.left = n2
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C++"
|
||||||
|
|
||||||
|
```cpp title="binary_tree.cpp"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
TreeNode* P = new TreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1->left = P;
|
||||||
|
P->left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1->left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Java"
|
||||||
|
|
||||||
|
```java title="binary_tree.java"
|
||||||
|
TreeNode P = new TreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P;
|
||||||
|
P.left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C#"
|
||||||
|
|
||||||
|
```csharp title="binary_tree.cs"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
TreeNode P = new(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P;
|
||||||
|
P.left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Go"
|
||||||
|
|
||||||
|
```go title="binary_tree.go"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
p := NewTreeNode(0)
|
||||||
|
n1.Left = p
|
||||||
|
p.Left = n2
|
||||||
|
// Removing node P
|
||||||
|
n1.Left = n2
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Swift"
|
||||||
|
|
||||||
|
```swift title="binary_tree.swift"
|
||||||
|
let P = TreeNode(x: 0)
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P
|
||||||
|
P.left = n2
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "JS"
|
||||||
|
|
||||||
|
```javascript title="binary_tree.js"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
let P = new TreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P;
|
||||||
|
P.left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "TS"
|
||||||
|
|
||||||
|
```typescript title="binary_tree.ts"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
const P = new TreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P;
|
||||||
|
P.left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Dart"
|
||||||
|
|
||||||
|
```dart title="binary_tree.dart"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
TreeNode P = new TreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P;
|
||||||
|
P.left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Rust"
|
||||||
|
|
||||||
|
```rust title="binary_tree.rs"
|
||||||
|
let p = TreeNode::new(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.borrow_mut().left = Some(p.clone());
|
||||||
|
p.borrow_mut().left = Some(n2.clone());
|
||||||
|
// Removing node P
|
||||||
|
n1.borrow_mut().left = Some(n2);
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "C"
|
||||||
|
|
||||||
|
```c title="binary_tree.c"
|
||||||
|
/* Inserting and removing nodes */
|
||||||
|
TreeNode *P = newTreeNode(0);
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1->left = P;
|
||||||
|
P->left = n2;
|
||||||
|
// Removing node P
|
||||||
|
n1->left = n2;
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Kotlin"
|
||||||
|
|
||||||
|
```kotlin title="binary_tree.kt"
|
||||||
|
val P = TreeNode(0)
|
||||||
|
// Inserting node P between n1 and n2
|
||||||
|
n1.left = P
|
||||||
|
P.left = n2
|
||||||
|
// Removing node P
|
||||||
|
n1.left = n2
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Ruby"
|
||||||
|
|
||||||
|
```ruby title="binary_tree.rb"
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
=== "Zig"
|
||||||
|
|
||||||
|
```zig title="binary_tree.zig"
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
??? pythontutor "Code visualization"
|
||||||
|
|
||||||
|
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
|
||||||
|
It's important to note that inserting nodes may change the original logical structure of the binary tree, while removing nodes usually means removing the node and all its subtrees. Therefore, in a binary tree, insertion and removal are usually performed through a set of operations to achieve meaningful actions.
|
||||||
|
|
||||||
|
## Common types of binary trees
|
||||||
|
|
||||||
|
### Perfect binary tree
|
||||||
|
|
||||||
|
As shown in the figure below, in a "perfect binary tree," all levels of nodes are fully filled. In a perfect binary tree, the degree of leaf nodes is $0$, and the degree of all other nodes is $2$; if the tree's height is $h$, then the total number of nodes is $2^{h+1} - 1$, showing a standard exponential relationship, reflecting the common phenomenon of cell division in nature.
|
||||||
|
|
||||||
|
!!! tip
|
||||||
|
|
||||||
|
Please note that in the Chinese community, a perfect binary tree is often referred to as a "full binary tree."
|
||||||
|
|
||||||
|
![Perfect binary tree](binary_tree.assets/perfect_binary_tree.png)
|
||||||
|
|
||||||
|
### Complete binary tree
|
||||||
|
|
||||||
|
As shown in the figure below, a "complete binary tree" has only the bottom level nodes not fully filled, and the bottom level nodes are filled as far left as possible.
|
||||||
|
|
||||||
|
![Complete binary tree](binary_tree.assets/complete_binary_tree.png)
|
||||||
|
|
||||||
|
### Full binary tree
|
||||||
|
|
||||||
|
As shown in the figure below, a "full binary tree" has all nodes except leaf nodes having two children.
|
||||||
|
|
||||||
|
![Full binary tree](binary_tree.assets/full_binary_tree.png)
|
||||||
|
|
||||||
|
### Balanced binary tree
|
||||||
|
|
||||||
|
As shown in the figure below, in a "balanced binary tree," the absolute difference in height between the left and right subtrees of any node does not exceed 1.
|
||||||
|
|
||||||
|
![Balanced binary tree](binary_tree.assets/balanced_binary_tree.png)
|
||||||
|
|
||||||
|
## Degeneration of binary trees
|
||||||
|
|
||||||
|
The figure below shows the ideal and degenerate structures of binary trees. When every level of a binary tree is filled, it reaches the "perfect binary tree"; when all nodes are biased towards one side, the binary tree degenerates into a "linked list".
|
||||||
|
|
||||||
|
- The perfect binary tree is the ideal situation, fully leveraging the "divide and conquer" advantage of binary trees.
|
||||||
|
- A linked list is another extreme, where operations become linear, degrading the time complexity to $O(n)$.
|
||||||
|
|
||||||
|
![The Best and Worst Structures of Binary Trees](binary_tree.assets/binary_tree_best_worst_cases.png)
|
||||||
|
|
||||||
|
As shown in the table below, in the best and worst structures, the number of leaf nodes, total number of nodes, and height of the binary tree reach their maximum or minimum values.
|
||||||
|
|
||||||
|
<p align="center"> Table <id> The Best and Worst Structures of Binary Trees </p>
|
||||||
|
|
||||||
|
| | Perfect binary tree | Linked list |
|
||||||
|
| ----------------------------------------------- | ------------------- | ----------- |
|
||||||
|
| Number of nodes at level $i$ | $2^{i-1}$ | $1$ |
|
||||||
|
| Number of leaf nodes in a tree with height $h$ | $2^h$ | $1$ |
|
||||||
|
| Total number of nodes in a tree with height $h$ | $2^{h+1} - 1$ | $h + 1$ |
|
||||||
|
| Height of a tree with $n$ total nodes | $\log_2 (n+1) - 1$ | $n - 1$ |
|
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 42 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 25 KiB |
After Width: | Height: | Size: 26 KiB |
After Width: | Height: | Size: 17 KiB |
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 19 KiB |
After Width: | Height: | Size: 20 KiB |
After Width: | Height: | Size: 21 KiB |
After Width: | Height: | Size: 22 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 24 KiB |
@ -0,0 +1,89 @@
|
|||||||
|
# Binary tree traversal
|
||||||
|
|
||||||
|
From the perspective of physical structure, 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 to achieve.
|
||||||
|
|
||||||
|
Common traversal methods for binary trees include level-order traversal, preorder traversal, inorder traversal, and postorder traversal, among others.
|
||||||
|
|
||||||
|
## Level-order traversal
|
||||||
|
|
||||||
|
As shown in the figure below, "level-order traversal" traverses the binary tree from top to bottom, layer by layer, and accesses nodes in each layer in a left-to-right order.
|
||||||
|
|
||||||
|
Level-order traversal essentially belongs to "breadth-first traversal", also known as "breadth-first search (BFS)", which embodies a "circumferentially outward expanding" layer-by-layer traversal method.
|
||||||
|
|
||||||
|
![Level-order traversal of a binary tree](binary_tree_traversal.assets/binary_tree_bfs.png)
|
||||||
|
|
||||||
|
### 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:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{binary_tree_bfs}-[class]{}-[func]{level_order}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Complexity analysis
|
||||||
|
|
||||||
|
- **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 lowest level, the queue can contain at most $(n + 1) / 2$ nodes at the same time, occupying $O(n)$ space.
|
||||||
|
|
||||||
|
## Preorder, inorder, and postorder traversal
|
||||||
|
|
||||||
|
Correspondingly, preorder, inorder, and postorder traversal all belong to "depth-first traversal", also known as "depth-first search (DFS)", which embodies a "proceed to the end first, then backtrack and continue" traversal method.
|
||||||
|
|
||||||
|
The figure below shows the working principle of performing a depth-first traversal 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 traversal, inorder traversal, and postorder traversal.
|
||||||
|
|
||||||
|
![Preorder, inorder, and postorder traversal of a binary search tree](binary_tree_traversal.assets/binary_tree_dfs.png)
|
||||||
|
|
||||||
|
### Code implementation
|
||||||
|
|
||||||
|
Depth-first search is usually implemented based on recursion:
|
||||||
|
|
||||||
|
```src
|
||||||
|
[file]{binary_tree_dfs}-[class]{}-[func]{post_order}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! tip
|
||||||
|
|
||||||
|
Depth-first search can also be implemented based on iteration, interested readers can study this on their own.
|
||||||
|
|
||||||
|
The figure below 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>"
|
||||||
|
![The recursive process of preorder traversal](binary_tree_traversal.assets/preorder_step1.png)
|
||||||
|
|
||||||
|
=== "<2>"
|
||||||
|
![preorder_step2](binary_tree_traversal.assets/preorder_step2.png)
|
||||||
|
|
||||||
|
=== "<3>"
|
||||||
|
![preorder_step3](binary_tree_traversal.assets/preorder_step3.png)
|
||||||
|
|
||||||
|
=== "<4>"
|
||||||
|
![preorder_step4](binary_tree_traversal.assets/preorder_step4.png)
|
||||||
|
|
||||||
|
=== "<5>"
|
||||||
|
![preorder_step5](binary_tree_traversal.assets/preorder_step5.png)
|
||||||
|
|
||||||
|
=== "<6>"
|
||||||
|
![preorder_step6](binary_tree_traversal.assets/preorder_step6.png)
|
||||||
|
|
||||||
|
=== "<7>"
|
||||||
|
![preorder_step7](binary_tree_traversal.assets/preorder_step7.png)
|
||||||
|
|
||||||
|
=== "<8>"
|
||||||
|
![preorder_step8](binary_tree_traversal.assets/preorder_step8.png)
|
||||||
|
|
||||||
|
=== "<9>"
|
||||||
|
![preorder_step9](binary_tree_traversal.assets/preorder_step9.png)
|
||||||
|
|
||||||
|
=== "<10>"
|
||||||
|
![preorder_step10](binary_tree_traversal.assets/preorder_step10.png)
|
||||||
|
|
||||||
|
=== "<11>"
|
||||||
|
![preorder_step11](binary_tree_traversal.assets/preorder_step11.png)
|
||||||
|
|
||||||
|
### 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 degrades into a linked list, the recursion depth reaches $n$, the system occupies $O(n)$ stack frame space.
|
@ -0,0 +1,9 @@
|
|||||||
|
# Tree
|
||||||
|
|
||||||
|
![Tree](../assets/covers/chapter_tree.jpg)
|
||||||
|
|
||||||
|
!!! abstract
|
||||||
|
|
||||||
|
The towering tree, full of vitality with its roots deep and leaves lush, branches spreading wide.
|
||||||
|
|
||||||
|
It vividly demonstrates the form of data divide-and-conquer.
|
@ -0,0 +1,54 @@
|
|||||||
|
# Summary
|
||||||
|
|
||||||
|
### Key review
|
||||||
|
|
||||||
|
- A binary tree is a non-linear data structure that reflects the "divide and conquer" logic of splitting one into two. Each binary tree node contains a value and two pointers, which point to its left and right child nodes, respectively.
|
||||||
|
- For a node in a binary tree, the tree formed by its left (right) child node and all nodes under it is called the node's left (right) subtree.
|
||||||
|
- Related terminology of binary trees includes root node, leaf node, level, degree, edge, height, and depth, among others.
|
||||||
|
- The operations of initializing a binary tree, inserting nodes, and removing nodes are similar to those of linked list operations.
|
||||||
|
- Common types of binary trees include perfect binary trees, complete binary trees, full binary trees, and balanced binary trees. The perfect binary tree represents the ideal state, while the linked list is the worst state after degradation.
|
||||||
|
- A binary tree can be represented using an array by arranging the node values and empty slots in a level-order traversal sequence and implementing pointers based on the index mapping relationship between parent nodes and child nodes.
|
||||||
|
- The level-order traversal of a binary tree is a breadth-first search method, which reflects a layer-by-layer traversal manner of "expanding circle by circle." It is usually implemented using a queue.
|
||||||
|
- Pre-order, in-order, and post-order traversals are all depth-first search methods, reflecting the traversal manner of "going to the end first, then backtracking to continue." They are usually implemented using recursion.
|
||||||
|
- A binary search tree is an efficient data structure for element searching, with the time complexity of search, insert, and remove operations all being $O(\log n)$. When a binary search tree degrades into a linked list, these time complexities deteriorate to $O(n)$.
|
||||||
|
- An AVL tree, also known as a balanced binary search tree, ensures that the tree remains balanced after continuous node insertions and removals through rotation operations.
|
||||||
|
- Rotation operations in an AVL tree include right rotation, left rotation, right-then-left rotation, and left-then-right rotation. After inserting or removing nodes, an AVL tree performs rotation operations from bottom to top to rebalance the tree.
|
||||||
|
|
||||||
|
### Q & A
|
||||||
|
|
||||||
|
**Q**: For a binary tree with only one node, are both the height of the tree and the depth of the root node $0$?
|
||||||
|
|
||||||
|
Yes, because height and depth are typically defined as "the number of edges passed."
|
||||||
|
|
||||||
|
**Q**: The insertion and removal in a binary tree are generally completed by a set of operations. What does "a set of operations" refer to here? Can it be understood as the release of resources of the child nodes?
|
||||||
|
|
||||||
|
Taking the binary search tree as an example, the operation of removing a node needs to be handled in three different scenarios, each requiring multiple steps of node operations.
|
||||||
|
|
||||||
|
**Q**: Why are there three sequences: pre-order, in-order, and post-order for DFS traversal of a binary tree, and what are their uses?
|
||||||
|
|
||||||
|
Similar to sequential and reverse traversal of arrays, pre-order, in-order, and post-order traversals are three methods of traversing a binary tree, allowing us to obtain a traversal result in a specific order. For example, in a binary search tree, since the node sizes satisfy `left child node value < root node value < right child node value`, we can obtain an ordered node sequence by traversing the tree in the "left → root → right" priority.
|
||||||
|
|
||||||
|
**Q**: In a right rotation operation that deals with the relationship between the imbalance nodes `node`, `child`, `grand_child`, isn't the connection between `node` and its parent node and the original link of `node` lost after the right rotation?
|
||||||
|
|
||||||
|
We need to view this problem from a recursive perspective. The `right_rotate(root)` operation passes the root node of the subtree and eventually returns the root node of the rotated subtree with `return child`. The connection between the subtree's root node and its parent node is established after this function returns, which is outside the scope of the right rotation operation's maintenance.
|
||||||
|
|
||||||
|
**Q**: In C++, functions are divided into `private` and `public` sections. What considerations are there for this? Why are the `height()` function and the `updateHeight()` function placed in `public` and `private`, respectively?
|
||||||
|
|
||||||
|
It depends on the scope of the method's use. If a method is only used within the class, then it is designed to be `private`. For example, it makes no sense for users to call `updateHeight()` on their own, as it is just a step in the insertion or removal operations. However, `height()` is for accessing node height, similar to `vector.size()`, thus it is set to `public` for use.
|
||||||
|
|
||||||
|
**Q**: How do you build a binary search tree from a set of input data? Is the choice of root node very important?
|
||||||
|
|
||||||
|
Yes, the method for building the tree is provided in the `build_tree()` method in the binary search tree code. As for the choice of the root node, we usually sort the input data and then select the middle element as the root node, recursively building the left and right subtrees. This approach maximizes the balance of the tree.
|
||||||
|
|
||||||
|
**Q**: In Java, do you always have to use the `equals()` method for string comparison?
|
||||||
|
|
||||||
|
In Java, for primitive data types, `==` is used to compare whether the values of two variables are equal. For reference types, the working principles of the two symbols are different.
|
||||||
|
|
||||||
|
- `==`: Used to compare whether two variables point to the same object, i.e., whether their positions in memory are the same.
|
||||||
|
- `equals()`: Used to compare whether the values of two objects are equal.
|
||||||
|
|
||||||
|
Therefore, to compare values, we should use `equals()`. However, strings initialized with `String a = "hi"; String b = "hi";` are stored in the string constant pool and point to the same object, so `a == b` can also be used to compare the contents of two strings.
|
||||||
|
|
||||||
|
**Q**: Before reaching the bottom level, is the number of nodes in the queue $2^h$ in breadth-first traversal?
|
||||||
|
|
||||||
|
Yes, for example, a full binary tree with height $h = 2$ has a total of $n = 7$ nodes, then the bottom level has $4 = 2^h = (n + 1) / 2$ nodes.
|