Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Red-Black tree balanced

I am studying red-black trees and I am reading the Cormen's "Introduction to Algorithms" book. Now I am trying to create red-black tree with numbers 1-10 by using the pseudo-code described in the book - RB-INSERT-FIXUP(T, z). Here is the screenshot enter image description here

Everything was fine until I inserted number "6" into the tree. According to pseudo-code I get the following result

enter image description here

As you can see all red-black tree requirements met, but I am confused because I know that red-black tree should be balanced on each step.

I can manually perform "left-rotate" procedure with "2" and "4" and change the colours. In that case I will get the following result, which is balanced appropriately

enter image description here

So my question is:

Is that all right to have unbalanced tree?, or I missed something during insertion nodes?

like image 272
Ashot Khachatryan Avatar asked Feb 15 '15 20:02

Ashot Khachatryan


People also ask

Does a red-black tree have to be balanced?

In computer science, a red–black tree is a kind of self-balancing binary search tree. Each node stores an extra bit representing "color" ("red" or "black"), used to ensure that the tree remains balanced during insertions and deletions.

How unbalanced can a red-black tree get?

I think rb tree can become unbalanced up to 2 log n in depth. you should check this. a perfectly balanced tree is roughly log n in depth. unbalanced-ness in rb tree is not bad enough to screw up it's big O for various operations.

Why is red-black tree a self-balancing tree?

A red-black tree is a kind of self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the color (red or black). These colors are used to ensure that the tree remains balanced during insertions and deletions.

Which tree is balanced tree?

A balanced binary tree will follow the following conditions: The absolute difference of heights of left and right subtrees at any node is less than 1. For each node, its left subtree is a balanced binary tree. For each node, its right subtree is a balanced binary tree.


1 Answers

This is fine. Red-black trees are balanced, but not necessarily perfectly. To be precise, properties of red-black tree guarantee that the longest path to the leaf (implicit, not shown in your picture) is at most twice as long as the shortest. Shortest one has length 2 (2 -> 1 -> leaf), longest one has length 4 (2 -> 4 -> 5 -> 6 -> leaf), so the invariant does hold.

like image 101
Marcin Łoś Avatar answered Nov 15 '22 11:11

Marcin Łoś