Binary search tree and red-black tree

Binary search tree

1. The values ​​of all nodes on the left subtree are less than or equal to the value of its root node;
2. The values ​​of all nodes on the right subtree are greater than or equal to the value of its root node;
3. The left and right subtrees are also Must be a binary sort tree respectively;

Red-black tree (balanced binary tree)

1. The node is red or black;
2. The root node is black;
3. The node of each leaf is a black empty node (NULL);
4. The two child nodes of each red node are black (from each leaf There can be no two consecutive red nodes on all paths to the follower) (that is, for layers except for NIL nodes, red and black nodes are alternated. If the first layer is a black node, the next layer must be a red node, and vice versa. Same);
5. All paths from any node to each leaf contain the same black node;

Red-black tree insertion summary:

1. When a new node appears, it is inserted in red by default. If its parent node is red, it will recursively change its color upwards. If the root node becomes red as a result, rotate the root node to the left (the right side is too dark) or After turning right (the left side is too dark), modify the color downward from the root node;
2. From the root node, check whether the number of black nodes on the path is consistent, if not, then rotate the node left (the number of black nodes on the right is more) Or rotate right (the number of black nodes on the left is more) and change the color, repeat 2 operations until it meets the red-black tree rules;

Guess you like

Origin blog.csdn.net/weixin_39195030/article/details/103874752