Deleting a Node from a Binary Search Tree (Scheme

  • 4,230 views
Uploaded 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.

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.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
4,230
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
29
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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