Red and black Trees

Source: Internet
Author: User

1. Nature

A red-black tree is a binary lookup tree, but each node adds a field that represents the node color (red or black) and satisfies the criteria:

    • Each node is either red or black.
    • The root node is black.
    • Each leaf node (NIL) is black.
    • If a node is red, then its two sons are black.
    • For each node, the same number of black nodes are included on all paths from that node to its descendants

To facilitate the processing of boundary conditions, we use a Sentinel to represent nil, if a node does not have a child node or a parent node, then the corresponding pointer of the junction points to nil.

The height of a red-black tree with n internal nodes (excluding nil) is 2LG (n+1).

2. Rotate

When you perform an INSERT or delete operation on a red-black tree, the results may violate the nature of the red-black tree, and we need to change the tree's pointer structure to preserve the nature of the red-black tree. Rotation is the correction process will be used in the operation, divided into left and right, here only to describe the left-hand operation, right-handed just opposite to the left-hand operation. The following are the rotated

  

left-ROTATE (T, x)    y←right[x]    right[x]←left[x]    if left[y]! = Nil[t]        P[left[y] ]←x    p[y]←p[x]    if p[x] = nil[t]        root[t]←y    Elseif x = Left[p[x]]        left[p[x]]←y    else  right[p[x]]←y        left[y]←x    p[x]←y 

3. Insert

The insert operation is close to the normal binary tree insert operation, setting the new insertion node to red (as little as possible against the binary tree nature), and adding Rb-insert-fixup (T, z) at the end to adjust the binary tree to satisfy the nature of the red-black tree.

rb-INSERT y←nil[t] x←root[t] whileX! =Nil[t] Doy←xifKEY[Z] <Key[x] x←left[x]ElseX←right[x] P[z]←yify =Nil[t] root[t]=ZElse ifKEY[Z] <Key[y] Left[y]←zElseright[y]←z left[z]←nil[t] right[z]←nil[t] color[z]←red RB-insert-fixup (T, z)

Red and black Trees

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.