Red-Black Tree is a self-balancing Binary Search Tree in which each node has one additional color attribute, either red or black, to ensure that the tree is balanced over time. The balance is achieved by applying specific rules during the insertion and deletion operations that ensure that the height of the tree remains logarithmic, O(log n), where n is the number of elements in the tree.
The main properties of Red-Black Tree are:
An example of a Red-Black Tree:
Let’s say we want to insert the following elements in a Red-Black Tree: 30, 40, 50, 20, 60, 70, 10, 25.
We start by creating a new node for 30 and color it black since it is the root of the tree.
30(B)
Insert 40 as its right child and color it red.
30(B)
40(R)
Insert 50 as the right child of 40 and color it black.
30(B)
40(B)
50(R)
Insert 20 as the left child of 30 and color it black.
30(B)
/
20(B) 40(B)
50(R)
Insert 60 and color it red as the right child of 50. Then, apply a Left Rotation on node 40 to fix the violation of the Black Height property.
30(B)
/
20(B) 50(B)
/
40(R) 60(R)
Insert 70 as the right child of 60 and color it black.
50(B)
/
30(R) 60(B)
/ \
20(B) 40(B) 70(R)
Insert 10 as the left child of 20 and color it red. Then, apply a Right Rotation on node 30 and a Left Rotation on node 50 to fix the double violation of the Red-Black Tree properties.
50(B)
/
30(R) 60(B)
/ \
20(B) 40(B) 70(R)
/
10(R)
What is a Red-Black Tree?
Answer: A Red-Black Tree is a self-balancing binary search tree with each node colored either red or black, ensuring that the tree is height-balanced and closely resembles a balanced tree.
What is the maximum height of a Red-Black Tree with N nodes?
Answer: The maximum height of a Red-Black Tree with N nodes is 2*log(N+1).
How are nodes colored in a Red-Black Tree?
Answer: Nodes in a Red-Black Tree are colored either red or black, with the color chosen based on certain conditions: the root is always black, all leaves are black, and if a node is red, then both its children must be black.
What are the operations that can be performed on a Red-Black Tree?
Answer: The operations that can be performed on a Red-Black Tree include insertion, deletion, searching, traversal, and rotation.
How does rotation help balance a Red-Black Tree?
Answer: Rotation helps balance a Red-Black Tree by re-positioning nodes to maintain the red-black property while preventing the height of the tree from exceeding log(N) with N nodes. Rotation can be performed in two ways: left-rotation and right-rotation.