Upcoming SlideShare
×

# Deleting a Node from a Binary Search Tree (Scheme

5,870 views

Published on

Explains how to delete a node from a binary search tree. The code is written in Scheme. The presentation is a supplement to my CS115 lecture.

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
5,870
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
37
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Deleting a Node from a Binary Search Tree (Scheme

1. 1. Deleting a Node from a BST<br />Allan Caine<br />November 11, 2009<br />
2. 2. Four Cases<br />2<br />
3. 3. Both Subtrees Empty<br />X<br />Empty<br />Empty<br />Empty<br />3<br />
4. 4. Left Subtree non-EmptyRight Subtree Empty<br />X<br />L<br />L<br />Empty<br />4<br />
5. 5. Left Subtree EmptyRight Subtree non-Empty<br />X<br />R<br />R<br />Empty<br />5<br />
6. 6. Left and Right Subtrees non-Empty<br />X<br />X<br />R<br />L<br />L<br />New Root<br />6<br />?<br />?<br />
7. 7. Continuing with the Recursive Case<br />Root<br />7<br />New Root<br />New Root<br />These nodesare the same.<br />New Root<br />L’<br />R’<br />Empty<br />Empty<br />Empty<br />Empty<br />L<br />New Root<br />New Root<br />L’<br />?<br />?<br />?<br />?<br />
8. 8. Remove Root Code<br />(define (remove-root abst)<br /> (cond<br /> [(empty? abst) empty]<br /> [(and (empty? (node-left abst))<br /> (empty? (node-right abst))) empty]<br /> [(empty? (node-left abst)) (node-right abst)]<br /> [(empty? (node-right abst)) (node-left abst)]<br /> [else (make-node (node-key (node-right abst))<br /> (node-value (node-right abst))<br /> (node-left abst)<br /> (remove-root (node-right abst)))]))<br />8<br />
9. 9. The Search Routine<br />(define (remove-key n abst)<br /> (cond<br /> [(empty? abst) empty]<br /> [(= n (node-key abst)) (remove-root abst)]<br /> [(&lt; n (node-key abst)) (make-node (node-key abst)<br /> (node-value abst)<br /> (remove-key n (node-left abst))<br /> (node-right abst))]<br /> [else (make-node (node-key abst)<br /> (node-value abst)<br /> (node-left abst)<br /> (remove-key n (node-right abst)))]))<br />9<br />