Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Advanced Tree Structures

Advanced Tree Structures

After mastering basic tree structures such as binary trees and binary search trees, we are about to step into a broader and more efficient field - advanced tree structures.

If basic trees are ordinary roads in the world of data structures, then advanced tree structures are carefully designed highways and overpasses, which through clever balancing rules and storage strategies ensure excellent performance even with huge data volumes or frequent operations.

This chapter introduces AVL trees、Red-black trees、B-trees and B+ trees these four classic advanced tree structures.


Why do we need advanced tree structures?

Before diving deeper, let's ask a question: with an efficient binary search tree (BST), why do we need more complex trees?

Imagine you have a library that uses a BST to store books sorted by title. If you insert them one by one in alphabetical order (e.g.:A..., B..., C...), this tree will degenerate into a chain (similar to a linked list). At this point, the time to find a book will deteriorate from the ideal O(log n) to the worst-case O(n), which is extremely inefficient.

Figure: Illustration of a binary search tree degenerating into a linked list when inserting sorted data, causing degraded search performance.

Advanced tree structures (self-balancing trees) were created to solve this problem. They automatically adjust the tree's shape when nodes are inserted or deleted, keeping the tree balanced, thereby ensuring the time complexity of operations such as search, insert, and delete always remains at O(log n) level.


AVL tree: the guardian of height balance

The AVL tree was the first self-balancing binary search tree invented, named after its inventors Adelson-Velsky and Landis.

The core idea of the AVL tree is very simple:For any node in the tree, the height difference between its left and right subtrees cannot exceed 1。

Core concept: balance factor

Each node has a balance factor, calculated as: 平衡因子 = 左子树高度 - 右子树高度 In an AVL tree, each node's balance factor can only be -1, 0, or 1.

Imbalance and rotation adjustment

After inserting or deleting a node, if a node's balance factor becomes 2 or -2, the tree is unbalanced. To restore balance, the AVL tree uses four types ofRotateoperations to adjust:

Example

class

AVLNode:

   

def

init

(

self

,

key

)

:

       

self

.

key

=

key

       

self

.

height

=

1

 

node height, initially 1

       

self

.

left

=

None

       

self

.

right

=

None

def

get_height

(

node

)

:

   

"""Get node height (handle empty nodes)"""

   

return

node.

height

if

node

else

0

def

get_balance_factor

(

node

)

:

   

"""Calculate a node's balance factor"""

   

if

not

node:

       

return

0

   

return

get_height

(

node.

left

)

(

node.

right

)

def

right_rotate

(

y

)

:

   

"""
    Perform a right rotation on the subtree rooted at y
         y                              x
        / \                          /   \
       x T4 rotate right (y) z y
      / \      - - - - - - - ->    / \  / \
     z   T3                       T1  T2 T3 T4
    / \
  T1   T2
    """

    x

=

y.

left

    T3

=

x.

right

   

Perform rotation

    x.

right

=

y

    y.

left

=

T3

   

Update heights (must update y's height before x's height)

    y.

height

=

1

max

(

get_height

(

y.

left

)

,

get_height

(

y.

right

)

)

    x.

height

=

1

max

(

get_height

(

x.

left

)

,

get_height

(

x.

right

)

)

   

Return the new root node

   

return

x

The left rotation function is symmetric to the right rotation; detailed implementation omitted here

def

left_rotate

(

x

)

:

   

"""Perform a left rotation on the subtree rooted at x (logic symmetric to right rotation)"""

   

pass

Summary of AVL tree characteristics

Feature Description
Strict balance Strict balance condition (height difference <= 1), tree height is closest to log n, excellent search performance.
Frequent adjustments After insert/delete, multiple rotations from bottom to top may be needed to restore balance.
Applicable scenarios Suitable forMany queries, few insertions/deletionsscenarios, such as the middle layer of database indexes or lookup tables in memory.

Red-black tree: the king of engineering practice

The red-black tree is another self-balancing binary search tree that makes some "compromises" based on the AVL tree. It does not pursue absolute balance like the AVL tree, but ensures approximate balance through a looser set of rules, reducing the number of rotations during insert/delete and achieving better engineering results in overall performance. Java's TreeMap、TreeSet and C++ STL's map、set both use red-black trees at the underlying level.

The five core rules of red-black trees

Red-black trees maintain balance by adding a color attribute (red or black) to nodes and following these rules:

Rules 4 and 5 are key to red-black tree balance. Rule 5 ensures no path is more than twice as long as any other, achieving approximate balance.

Insertion adjustment strategy

When inserting a new node, we always first color itRed(to avoid violating rule 5). If this causes a conflict (mainly violating rule 2 or rule 4), it needs to be resolved throughrecoloringandRotateto adjust. The core idea is to continuously "move" the conflict (red) upward toward the root until it can be resolved by recoloring or rotation.

Example

class

RBNode:

    RED

=

"RED"

    BLACK

=

"BLACK"

   

def

init

(

self

,

key

)

:

       

self

.

key

=

key

       

self

.

color

=

self

.

RED

 

New node is initially red

       

self

.

left

=

None

       

self

.

right

=

None

       

self

.

parent

=

None

 

Red-black trees need parent node pointers

def

insert_fixup

(

tree

,

node

)

:

   

"""Restore red-black tree properties after insertion (simplified logical description)"""

   

while

node.

parent

and

node.

parent

.

color

==

RBNode.

RED

:

       

Case 1: uncle node is red -> recolor

       

Case 2 & 3: uncle node is black -> resolve through rotation and recoloring

       

... (the actual implementation involves extensive pointer operations; this is a logical description)

       

pass

    tree.

root

.

color

=

RBNode.

BLACK

 

Ensure the root node is black

Red-black tree vs AVL tree

Feature AVL trees Red-black trees
Balance criterion Strict (height difference <= 1) Loose (approximate balance via color rules)
Search performance Better(tree is more balanced) Slightly inferior, but still O(log n)
Insert/delete may requiremore rotations fewer rotations,higher efficiency
Applicable scenarios scenarios requiring frequent searches scenarios requiring high overall performance, such as language standard libraries and file systems

B-trees and B+ trees: the engines of disk storage

When the data volume is too large to fit entirely in memory, it must be stored on disk. Disk I/O (read/write) is much slower than memory access. B-trees and B+ trees are designed toreduce the number of disk I/O operationsand aremulti-way balanced search trees, and they are widely used for indexing in databases and file systems.

B-tree: balanced multi-way search tree

A B-tree no longer has only one piece of data and two pointers per node. An m-order B-tree node has the following properties:

Figure: Illustration of the structure of a 3-order B-tree node. It contains two keys and three pointers, dividing the data range into three intervals.

The advantage of B-treeslies in their short, wide shape. Since a node can store multiple keys and have multiple children, the tree height is greatly reduced. When searching for data, fewer disk pages (nodes) need to be loaded, improving efficiency.

B+ tree: an upgraded version of the B-tree

The B+ tree makes key improvements on the basis of the B-tree and is thede facto standard。

Core differences between B+ trees and B-trees:

  1. Data storage location: In a B+ tree,all data records (or pointers to records) are stored only in leaf nodes. Internal nodes (non-leaf nodes) store only keys for routing.
  2. Leaf node linked list: all leaf nodes are connected by pointers into anordered doubly linked list。

Figure: Illustration of a B+ tree. Note that data is only in leaf nodes, and leaf nodes form an ordered linked list.

Great advantages of B+ trees

Advantage Explanation
More stable query efficiency Any search must reach a leaf node; path lengths are the same, giving stable performance.
Higher space utilization Internal nodes store no data, can hold more keys, the tree is shorter, and I/O is reduced.
Powerful range queries Through the linked list of leaf nodes, one can efficiently performWHERE age BETWEEN 20 AND 30range queries like this, while a B-tree requires complex in-order traversal.
Better suited for disk read-ahead Disks read and write by page (block). B+ tree nodes are usually designed to be exactly one page in size, so one I/O can load more keys, further reducing I/O.

Summary

Let's review these four advanced tree structures with a table:

Tree structure Core goal Key characteristics Typical application
AVL tree Ultimate query speed Strict height balance, frequent rotation adjustments Scenarios requiring fast lookups in memory
Red-black trees Balanced overall performance Approximate balance via color rules, high insert/delete efficiency Language standard libraries (Map/Set), process scheduling
B-tree Reduce disk I/O Multi-way balanced, data can be stored in internal nodes Early file systems, some database indexes
B+ tree Optimize database indexes Data only in leaves, leaves form a linked list, strong range queries Modern relational database (MySQL, PostgreSQL) indexes