Professional Documents
Culture Documents
Quiz3!
Midterm!
Assignment2!
(most) Quiz4!
Balanced trees:
Red-Black Trees
Definitions Insertion In a nutshell
Definition: an extended Node
Before, all our nodes were born equals.
5 13
← needs two fake children
In practice,
13 7 don’t bother
drawing them.
6 9
Balanced trees: Red-black trees
Definition: Red-Black Tree
• Each node must have exactly two children. For each child
that is lacking, you create a fake black one.
Violation!
• If z has a red uncle: colour the parent and uncle black, and grandparent red.
• If z has a red uncle: colour the parent and uncle black, and grandparent red.
• If z is a left child and has a black uncle: colour the parent black and the
grandparent red, then rotateRight(z.parent.parent)
• If z has a red uncle: colour the parent and uncle black, and grandparent red.
• If z is a right childand
left child andhas
hasa ablack
blackuncle:
uncle,colour
then rotateLeft(z.parent)
the parent black andand
the
grandparent red, then rotateRight(z.parent.parent)
7
12 Double red violation!
It also shows it’s
unbalanced…
7
4
9
3
5
6
2
1
You can’t have O(1) for both. If you want to optimize one
But with a balanced tree you operation, go for arrays or simple
get O(log n). pointers. Beyond, use a tree.
2a) Write a method showPath(int key1, int key2) that will show the keys
on the path from key1 to key2. Assume both keys exist.
2b) Write showPathReverse(int key1, int key2) that will show the keys in
the other order (from key2 to key1).