"Deciphering the Red-Black Tree in STL": Exploring the Red-Black Tree Implementation of STL in C++

"Deciphering the Red-Black Tree in STL": Exploring the Red-Black Tree Implementation of STL in C++

The red-black tree is a self-balancing binary search tree. Compared with ordinary binary search trees, it can maintain balance, so basic operations such as query and insertion can still guarantee O(logN) time in the worst case the complexity. Red-black trees are used in STL to implement many key data structures, such as map and set. So, how to implement the red-black tree?

STL defines the node structures _Rb_tree_node_base and _Rb_tree_node in the header file <stl_tree.h>, where _Rb_tree_node_base encapsulates a pointer to the parent node, left node, and right node, and _Rb_tree_node inherits from _Rb_tree_node_base and encapsulates a value , representing the stored data. In addition to the conventional node structure, the red-black tree also needs to record two key information: the root node root and the number of nodes node_count. This information is encapsulated in another structure _Rb_tree_impl.

struct _Rb_tree_impl {
    typedef _Rb_tree_node_base* _Base_ptr;
    _Base_ptr _M_header; // 头节点,不存储值
    _Base_ptr _M_node_count; // 节点数量
};

We can see that _Rb_tree_impl provides two pointers, and _M_header points to the pseudo-root node (header) of the red-black tree. This node does not actually store data, but is only used as an auxiliary node. _M_node_count is used to record the number of nodes.

Next, we need to identify five properties of a red-black tree:

  1. Each node is either red or black.
  2. The root node is black.
  3. Each leaf node (NIL node, empty node y

Guess you like

Origin blog.csdn.net/Jack_user/article/details/132294078