The tree in the data structure

Source: Internet
Author: User

Statement:

Respect the original, reprint please indicate the source http://blog.csdn.net/lizo_is_me/article/details/44260025

1 balanced two-pronged tree

Balanced binary trees (Balanced binary tree) were first proposed by Adelson-Wells and Landis (Adelson-velskii and Landis) in 1962, so they are also known as AVL trees.

Definition: Balance a binary tree or an empty tree, or a two-fork sort tree for the following properties:

(1) The absolute value of the difference between the left and right sub-tree depth is not more than 1;

(2) The left and right sub-tree is still a balanced binary tree.

  平衡因子BF=左子树深度-右子树深度.

The equilibrium factor of each node of the balanced binary tree can only be 1,0,-1. If the absolute value exceeds 1, the two-fork sort tree is unbalanced.

1.1 Ideas

If a new node is inserted into the balanced binary tree, the balance of the balanced binary tree is destroyed. The first thing to find is the pointer to the root node that loses balance after inserting a new node. Then adjust the link relationship between the nodes in this subtree to make it a new balance subtree. When the lost balance of the most small tree is adjusted to balance the subtree, the original other unbalanced subtree without adjustment, the entire binary sorting tree becomes a balanced binary tree.
The least-balanced tree is a subtree that is closest to the insertion node and has an absolute value greater than 1 of the balance factor as the root. Assuming that a represents the root node of the least-balanced tree, the action of adjusting the subtree can be summarized in the following four cases.

ll-type rotation

Because the node f is inserted on the left child B of a, the balance factor of a increases from 1 to 2 and loses balance. Therefore, a clockwise rotation operation is required. The left child B of a will rotate to the right to replace a as the root node, and a to the right down to the root node of the right subtree of B. and the right sub-tree of B turns into a's left subtree.

RR type rotation

Because the node f is inserted in right child C of a, the balance factor of a is reduced from 1 to 2. Therefore, a counterclockwise rotation operation is required. The right child c of a will rotate to the left up instead of a as the root node, and a to the left is the root node of the left subtree of c. The original C's left subtree becomes the right subtree of a.

LR type rotation

Due to the insertion of node F on the right number of the left child B of a, the balance factor of a increases from 1 to 2 and loses balance. It is necessary to perform two rotation operations (first counterclockwise, then clockwise). That is, first, the right subtree of the left child B of the A node, the root node D to the left up to the position of the B node, and then the D node to the right up to the point of rotation to the position of a node. That is, first make it a ll type, and then the LL-type treatment.

RL Type rotation

Because the node f is inserted on the left subtree of right child c of a, the balance factor of a is reduced from 1 to 2. It is necessary to perform two rotations (clockwise, counterclockwise), i.e. the root node d of the right child C of the a node is lifted to the right up to the C node position, and then the D node is rotated to the left up to the position of a node. The first is to make it a RR type, and then the RR type processing.

Summary

1. There are also 2 basic rotary L-shaped and R-type rotation, relatively simple is not said
The 2.LL and RR types are actually symmetrical, and so are LR and RL.
Type 3.LL is not said first L rotation and then l rotation, which means that causes imbalance of the cause from the child L children, and its corresponding rotation mode

2 Red and black trees

Red and black trees are a very interesting and balanced search tree. Its statistical performance is better than that of balanced binary trees (some books are called avl-trees according to the author's name, Adelson-velskii and Landis), so red and black trees are used in many places. Java's treemap is based on the red-black tree, in C + + STL, many parts (currently including set, Multiset, map, multimap) have applied red-black tree variants (SGI STL in the red and black trees have some changes, these modifications provide better performance, and support for set operations).

The red and black trees are defined as follows:

A two-fork search tree that meets the following criteria is a red-black tree
* Each node is either "Red" or "black" (which will be explained later).
* All leaf nodes are empty nodes and are "black"
* If a node is "red", then its two sub-nodes are "black"
* (Note: That is, if the end is black, then its sub-nodes can be either red or black).
* Each simple path of a node to its descendant nodes contains the same number of "black" nodes.
* The root node is always "black".

The reason for being called a red-black tree is that each of its nodes is "shaded" in red or black. These node colors are used to detect the balance of the tree. However, it is important to note that the red and black tree is not a balanced binary tree, on the contrary, the red and black trees relaxed some of the requirements of the balanced binary tree, due to a certain limit of "imbalance", the performance of the red and black trees has been improved.
# #思想
The black node point from the root node to the leaf node is called the "black height" of the tree (black-height). The previous nature of the red-black tree guarantees that the path from the root node to the leaf node will not exceed twice times the length of any other path.

Let's explain this conclusion. Consider a red-black tree with a black height of 3: The shortest path length from the root node to the leaf node is obviously 2 (black-black-black) and the longest path is 4 (black-red-black-red-black). Because of the nature of 4, it is not possible to add more black nodes in the longest path, in addition, according to the nature of 3, the red node must be a sub-node is black, so in the same simple route is not allowed to have two consecutive red nodes. To sum up, the longest road we can build will be a red-black alternate path.

From this we can conclude that the shortest length of a simple path from root to leaf node is n-1 and the maximum length is 2 (n-1) for a given black height of n red-black tree.

In insert and delete operations, nodes may be rotated to preserve the balance of the tree. The average and worst search times for red and black trees are O (log2 N). Cormen [2001] gives a proof of this conclusion. In practical applications, the statistical performance of red-black trees is better than that of balanced binary trees, but the extreme performance is slightly worse.

The insertion process of nodes in red and black trees

The process of inserting a node is:

    • Search the insertion point in the tree
    • The new node replaces an existing empty node and will have two empty nodes as sub-nodes
    • The new node is marked in red, and the color of its parent node is determined by the definition of the red and black tree, and the tree is adjusted if necessary.

Note that empty nodes and null pointers are different. In a simple implementation, you can use a common node labeled black as the "lookout point" as the empty node mentioned earlier.

Adding two empty sub-nodes to a red node conforms to the Nature 4, and it is also important to ensure that the two sub-nodes of the red node are black (by Nature 3). However, when the parent node of a new node is red, inserting a red child node is a violation of the definition. There are two situations.

Case 1: The root node is inserted.

The original tree is an empty tree, this situation will only violate the nature of 2.
Countermeasures: Apply this node directly to black.

Case 2: The parent node of the inserted node is black.

This will not violate the nature of 2 and Nature 4, the red-black tree has not been destroyed.
Strategy: Do nothing.

Scenario 3: The parent node of the inserted node is red (then its grandfather node must be black)

It is divided into 2 cases: The Red Father node is the grandfather node left child or right child, according to symmetry, discuss one side on the line, take the left child as an example:
Put the pseudo-code first:

1  whileColor[p[z]] = RED//Father node is red2      Do ifP[Z] = Left[p[p[z]]//Red Father node is the grandfather node left child, at this time the grandfather node must be black3             Theny← Right[P[p[z]]//y represents the color of the Uncle node4                 ifColor[y] = RED//If the Uncle node is red5                    ThenColor[p[z]]←black//Father node set to black6Color[y]←black//Uncle node is set to black7Color[p[p[z]]]←red//Grandfather node set to red8Z←P[P[Z]]//Move the pointer z to the grandfather node to determine if the nature of the red and black tree satisfies9                 Else ifz = Right[P[z]]//If the Uncle node is blackTen                       ThenZ←P[Z]//If the z-pointer is the right child of the Father node, rotate left OneLeft-rotate (T, z) AColor[p[z]]←black//This time z is already the left child of the Red parent node, set its parent node to black -Color[p[p[z]]]←red//Grandfather node set to red -                       Right-rotate (T, P[p[z]])//Rotate its grandfather node right the     Else(Same as  ThenClause with "Right"  and "left"exchanged) -Color[root[t]]←black//finally set the root node to black

3.1 The Uncle node is red, then the father and the Uncle node is set to black, the grandfather node is set to red, in the grandfather's node to determine whether to meet the nature of the red black tree. The above code 3-6 line
3.2 The Uncle node is black, then also discuss whether the current node is the left child, not the words will be left to rotate once, code 9-11 lines, itself if it is left children do not need, such as:

Then, does this look a bit like a balanced binary tree, LL-spin type? Just one more coloring step on that basis.

Does that satisfy the nature of the red-black tree?

Red-black tree removal process

The deletion of red and black trees is much more complicated than inserting, or it is based on the introduction of algorithmic analysis, such as the ordinary binary search tree, you need to first remove it from the two-fork tree, and then color adjustment to meet the above five properties.
There are four scenarios that need to be considered during the deletion process:
1. Only the left child exists
2. Only the right child exists
3. Two children are present
4. Two children do not exist
In the first two cases, simply point their child's parent node to their grandparent node, and if this is the third case, you need to find the node's successor, then replace the node with the successor node, the fourth is the simplest, and the child that corresponds to the parent node of the node is simply empty.

Rb-delete (T, z) The total operation of simply deleting nodes1 ifLEFT[Z] =NilTorRIGHT[Z] =NilT//If only left child or right child (not including null node) 2     ThenY←z//point Y to the node with delete 3    ElseY←tree-successor (z)//Otherwise points to the successor of Y, at which time Z has the condition of the child 4 ifLeft[y]≠NilT//If the left child of Y is not NULL, 5     ThenX←left[y]//The left child pointing to Y, this may only appear in the case of Y only left child 6    ElseX←right[y]//Otherwise point to right child, if Z only right child, then x refers to right child, other condition. X is an empty node 7P[x]←p[y]//Put Y's parent node to x, if z only left child right child, it means to replace him with his child node, otherwise the Y node is set to null 8 ifP[y] =NilT//indicates that the root node is deleted, then the X node is set to the root node 9     ThenRoot[t]←xTen    Else ify = Left[p[y]]//If the deletion is not a root node, the x node is used instead of the Point Y node, and the Y-node is not related to this lesson tree at this time. One             ThenLeft[p[y]]←x A            ElseRight[p[y]]←x - ifY≠z//If Y is not equal to Z, it is 3 lines inside, Y is the successor to X -     ThenKey[z]←key[y]//Copy the value of Y to Z and complete the deletion of the Z-node the         CopyY' s satellite data into z16 if color[y] = black and then Rb-delete-fixup (T, x) if the color of Y is black, then the deletion affects the balance of the tree, at which point X 118 return y is reduced for the height of the subtree of the node

There are 4 more cases when X is deleted:
The situation 1:x's brother W is red.
The case of 2:x's brother W is black, and the two children of W are black.
The case of 3:x's brother W is Black, W's left child is red, W's right child is black.
The case of 4:x's brother W is black, and W's right child is red.

Rb-delete-fixup (T, X)1  whileX≠ROOT[T] andCOLOR[X] = BLACK//At least X points to a black, which can cause imbalance, 2      Do ifx = Left[p[x]]//The node is left child 3            Thenw← Right[P[x]]//w represents its sibling node                 //case 1 4                ifCOLOR[W] = RED//If the sibling node is red 5                    ThenColor[w]←black//Change the color of W, and the color of its parent node 6Color[p[x]]←red7Left-rotate (T, p[x])//left-handed once, then turned into the following 3 cases 8w← Right[P[x]]///The following three cases are X's sibling node w is black, and 3 cases of child of its sibling node                 //case 2? 9                ifCOLOR[LEFT[W]] = BLACK andcolor[ Right[W]] = BLACKTen                    ThenColor[w]←red//W's 2 children are black, then set W to Red OneX←P[X]//case 3 A                   Else ifcolor[ Right[W]] = BLACK//w's right child is black. -                            ThenColor[left[w]]←black//w left child set to black -Color[w]←red//w set to red the                                 Right-rotate (T, W)//Rotate Right One time -w← Right[P[x]]Else    //case 4//w The right child is red -COLOR[W]←COLOR[P[X]]//Put the parent node color of x to W -Color[p[x]]←black//W set to Black +color[ Right[W]]←black//w's right child is set to black -Left-rotate (T, p[x])//Rotate left one time +X←ROOT[T]//Exit loop A        Else(Same as  ThenClause with "Right"  and "left"exchanged) atColor[x]←black

Simple analysis.
We use T (a) to represent a subtree of root nodes
# # #情况一: The brother W of X is red.

Simply stated below: Because T (x) height is reduced by 1.
So we use T (a) to rotate once, and change the W and A node color, at this time, such as the change, the subtree of the root node becomes w,t (W) of the right subtree height is not changed, or N,t (a) The right subtree of the height of n,t (a) Zuozi height is n-1, In this case, there are three other situations in which the structure can be processed. That is, after the change, the red box contains the subtree.
# # #情况二: X's brother W is black, and W's two children are black.

This is a simple case, the W is set to red directly, and T (a) is balanced, but if T (a) is just another tree's subtree, is the overall balance? For example, T (a) is the one in the case, so after processing, the whole is not balanced, so we need to set the X to a node, and then continue to determine whether the balance.

Case three: The Brother W of X is black, W's left child is red, W's right child is black


This situation may still cause a general imbalance.

The case of 4:x's brother W is black, and W's right child is red.


where w is the same color as the color A, so that the conversion fills the height of T (x), so that does not cause the overall imbalance, so directly exit the loop.

Summary:

1. When inserting, look at the parent node first: The parent node is black, direct plug, if the parent node is red, then look at the Uncle node, also divided into the Uncle node is red and black case
2. When the deletion, if only one child, then use the child to replace, otherwise, find its successor, to replace, and then see the node color deleted, if it is red, then do not change, if it is black, then look at the sibling node: Brother node is red, converted to Brother node is black, the brother node is black, The children of their sibling nodes are also discussed in 3 different situations.

B-and + + trees are in preparation:

The tree in the data structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.