14.red black tree - university of maryland · balanced bst unbalanced bst search: o(log n) search:...
TRANSCRIPT
Red&BlackTree
AnwarMamat
BST
BalancedBSTUnbalancedBST
Search:O(Logn) Search:O(n)
BalancedBinarySearchTree
• Red&BlackTree• AVLTree• 2-3Tree• B-tree
Red&BlackTree
• ABSTsuchthat:• Treeedgeshavecolor:RedorBlack• Nonodehastworededgesconnectedtoit.• Everypathfromroottonulllinkhasthesamenumberofblacklinks.• Redlinksleanleft.• NewnodeedgeisRed
Search:red-blackBSTs
• Observation.SearchisthesameasforelementaryBST(ignorecolor).
Red-blackBSTrepresentation
Elementaryred-blackBSToperations• Leftrotation.Orienta(temporarily)right-leaningredlinktoleanleft.
rotateEleft(before) rotateEleft(after)
Elementaryred-blackBSToperationscont.• Leftrotation.Orienta(temporarily)right-leaningredlinktoleanleft.
Elementaryred-blackBSToperationscont.• Rightrotation:Orientaleft-leaningredlinkto(temporarily)leanright.
rotateEleft(before) rotateEleft(after)
Elementaryred-blackBSToperationscont.• Rightrotation:Orientaleft-leaningredlinkto(temporarily)leanright.
Elementaryred-blackBSToperationscont.• Colorflip.
Colorflip(before) Colorflip (after)
Elementaryred-blackBSToperationscont.• Colorflip.
InsertioninaLLRBtree
• Rightchildred,leftchildblack:rotateleft.• Leftchild,left-left grandchildred:rotateright.• Bothchildrenred:flipcolors.
InsertioninaLLRBtree:Javaimplementation
R&BExample:Insertion
MInsert:M,D
D
R&BExample:Insertion
MInsert:M,X
X
RotateLeft
R&BExample:Insertion
Insert:M,X M
X
RotateLeft
R&BExample:Insertion
Insert:M,D,X
D
M
XD
M
X
Flip Color
R&BExample:Insertion
Insert:M,D,B
D
M
B
B
D
MFlip Color
RotateRight
R&BExample:Insertion
Insert:M,D,B
B
D
MFlip Color
B
D
M
R&BExample:Insertion
M,D,BInsertH
B
D
M
B
D
M
H
R&BExample:Insertion
M,D,B,HInsertS
B
D
M
H
B
D
M
H S
Colorflip
R&BExample:InsertionM,D,B,HInsertS
B
D
M
H S
Colorflip
B
D
M
H S
RotateLeft
R&BExample:InsertionM,D,B,HInsertS
B
D
M
H S
RotateLeft
B
D
M
H
S
R&BExample:InsertionM,D,B,H,SInsertE,K
B
D
M
H
S
B
D
M
H
S
E K
R&BExample:InsertionM,D,B,H,SInsertE,K
B
D
M
H
S
E K
B
D
M
H
S
E K
Color flip
RotateLeft
R&BExample:InsertionM,D,B,H,SInsertE,K
B
D
M
H
S
E D
B
D
M
HS
E
K
Rotateleft
R&BExample:InsertionM,D,B,H,SInsertE,K
B
D
M
HS
E
K
RotateRight
B
D M
H
SE K
R&BExample:InsertionM,D,B,H,S,E,K
B
D M
H
SE K B
D M
H
SE K
Color flip