Вы находитесь на странице: 1из 34

RED-BLACK TREES

BINARY SEARCH TREES REVIEW


1. Ordered, or sorted, binary trees.
BINARY SEARCH TREES REVIEW
1. Ordered, or sorted, binary trees.
2. Nodes can have 2 subtrees.
BINARY SEARCH TREES REVIEW
1. Ordered, or sorted, binary trees.
2. Nodes can have 2 subtrees.
3. Items to the left of a given node are smaller.
BINARY SEARCH TREES REVIEW
1. Ordered, or sorted, binary trees.
2. Nodes can have 2 subtrees.
3. Items to the left of a given node are smaller.
4. Items to the right of a given node are larger.
Balanced Search Trees
RED-BLACK TREE
1. Nodes are either red or black.
RED-BLACK TREE
1. Nodes are either red or black.
2. The root and leaves (NIL) are black.
RED-BLACK TREE
1. Nodes are either red or black.
2. The root and leaves (NIL) are black.
3. If a node is red, then its children are black.
RED-BLACK TREE
1. Nodes are either red or black.
2. The root and leaves (NIL) are black.
3. If a node is red, then its children are black.
4. All paths from a root to its NIL descendants contain the same
number of black nodes.
Nodes are either red or black.
root and leaves (NIL) are black

If a node is red, then its children are black

All paths from a root to its NIL


descendants contain the same
number of black nodes.
Extra info
1. Nodes require one storage bit to keep track of color
2. The longest path (root to farthest NIL) is no more than twice the
length of the shortest path (root to nearest NIL)
operations
Search
Insert
Remove
ROTATIONS
1. Rearranging subtrees.
2. Decrease the height.
 larger subtrees up and smaller subtrees down
3. Does not affect order of elements.
Left Rotations
Left Rotations
Right Rotation
Insertion
Red-Black trees are self-balancing
Quick review of relationship
Strategy
1. Insert Z and color it Red
2. Recolor and rotate nodes to fix violations
4 scenarios
1. Z is root
2. Z.uncle = red
3. Z.uncle = black (triangle)
4. Z.uncle = black (line)
Case 1: Z is root
Case 1: Z is root

Solution: color it black


Case 2: Z.uncle is red
Case 2: Z.uncle is red

Solution: Recolor Z.uncle and Z.parent


Z.Uncle = black (triangle)
Z.Uncle = black (triangle)
Z.Uncle = black (triangle)
Z.Uncle = black (line)
Z.Uncle = black (line)
Z.Uncle = black (line)
Some example insertions
Inserting: 15, 5, 1
Inserting: 8, 5, 15, 12, 19, 9, 13, 23 and then 10
Inserting: 5, 3, 8, 21, 22, 23, 24, and then 85

https://www.cs.usfca.edu/~galles/visualization/RedBlack.html