Javatpoint Logo
Javatpoint Logo

Insertion in Red-Black Tree using Python

Red-Black Trees

A red-black tree is a binary search tree with the additional property of being "nearly" adjusted. Every node in a red-black tree has a color, either red or black, and these colors are utilized to keep up with balance during insertions and deletions.

Red-Black Tree Insertion Algorithm:

  1. Begin at the root of the tree.
  2. Traverse the tree descending, following the binary search tree property, to track down the suitable area for the new node insertion.
  3. Embed the new node as a red leaf node.
  4. Fix any infringement of the red-black tree properties that might have been presented by the insertion utilizing a bunch of rotation and recoloring tasks.

Code

Output:

Insertion in Red-Black Tree using Python

Insertion:

BST Insertion:

Begin by inserting the new node as you would in a standard binary search tree (BST). Place the node in a suitable position in light of the examination of key qualities. Variety the Node-Red: Upon insertion, variety the recently inserted node as red. This may at first disregard a few properties of the red-black tree.

Fix Violations (Insert Fix):

To guarantee that the tree keeps up with the red-black properties, you want to play out a progression of recoloring and rotation tasks known as the "insert fix." This fix reestablishes the equilibrium and properties of the tree while obliging the new red node.

  1. Check assuming that the parent of the recently inserted node is likewise red. If it is, there's a possible violation of the red property.
  2. On the off chance that the parent's uncle is red, recolor the parent and uncle as black, and the grandparent as red. This keeps up with the black property along the way and helps in reestablishing the red property.
  3. On the off chance that the parent's kin is black or invalid, perform rotations and recoloring to reestablish harmony. Contingent upon whether the recently inserted node is the left child of its parent and the parent is the right child of its parent (as well as the other way around), perform proper rotations and recoloring.
  4. Rehash these means if vital, climbing the tree until all properties are reestablished.

Balancing the Tree: Recoloring and Rotation

Double Red:

When both the parent and uncle of the recently embedded node are red, recolor the parent and uncle to dark and the grandparent to red. This guarantees that the red property is reestablished. The cycle might go on up the tree to fix further lopsided characteristics.

Misalignment:

When the recently embedded node is the left child of a right child (or the other way around), rotations are performed to realign the tree. This keeps up with the dark property and guarantees balance.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA