This preview shows page 1. Sign up to view the full content.
Unformatted text preview: 31/5331 Tree-Insert(T, z)
n Insert z into tree T, and resulting tree still binary
15 6 3 2 18 7 17 20 13 4 Tree-Insert(T, 8)
Use Tree-search !
CSE 780 Algorithms Pseudocode
n Tree-insert(T, z) y = Nil, x = root[T]
while (x ≠ Nil)
do y=x Locate potential
parent y of z. if ( z.key < x.key )
then x = x.left
else x = x.right
z.parent = y
if (y = Nil) then root[T] = z Time:
O(h) else if (z.key < y.key)
then y.left = z
else y.right = z CSE 780 Algorithms Build Binary Search Tree CSE 780 Algorithms Deletion
6 3 2 18 7 17 13 4 9 20 16 23 delete 17??
4 CSE 780 Algorithms Three Cases for Deleting z
n Case 1: Leaf node
Case 2: Has only one child
n n Replace z with its child Case 3: Has both children
n Find its successor y
n n y cannot have left child!
replacing y with its right child! Replace z with y
The “replacement’’ is implemented
by the transplant operation
CSE 780 Algorithms Transplant Operation CSE 2331/5331 Case 3: More Detailed View
n Goal: delete node z
Let y be the successor of z
n y is the right child of z
Then replace z by y CSE 2331/5331 Case 3: cont.
n Case (3.b):
n y is not the right child of z
First replace y by its own right child, and then replace z
b y y. CSE 2331/5331 Delete together cover
Cases 1 & 2. Time complexity:
O(h) CSE 2331/5331 An Exercise Delete I ? Delete G ? Delete K ? Delete B ? CSE 2331/5331 Remarks
n All complexity depends on height h
h = (lg n), h = (n)
To guarantee performance:
n n Balanced tree ! Randomly build a tree
n Expected height is O(lg n)
Still problem: future insertions … CSE 780 Algorithms...
View Full Document
This document was uploaded on 02/24/2014 for the course CSE 2331 at Ohio State.
- Spring '12