Scheme: Remove the maximum from a BST

前端 未结 1 1124
醉话见心
醉话见心 2021-01-26 13:43

Good afternoon everyone,

I have very odd question and I\'m sorry If I have posted in a wrong part of the forum.

I\'m trying to understand remove-max f

相关标签:
1条回答
  • 2021-01-26 14:06

    Your function does not make any sense. It has typographical errors and doesn't handle empty trees as well as algorithmic errors such that it will produce invalid trees. It has poor use of abstractions which makes the code very difficult to read.

    From looking at it I have deduced that the model probably is:

    (define (node-empty? tree)
      (null? tree))
    
    (define (node-left tree)
      (car tree))
    
    (define (node-value tree)
      (cadr tree))
    
    (define (node-right tree)
      (caddr tree))
    
    (define (node left value right)
      (list left value right))
    

    It also seems like it follows the right node so I guess it removes tha maximum node from an ordered binary tree. Here is a correct version:

    (define (remove-max-bst tree)
      (cond
        ((node-empty? tree) tree)
        ((node-empty? (node-right tree))
         (node-left tree))
        (else
         (node (node-left tree)
               (node-value tree)
               (remove-max-bst (node-right tree))))))
    

    We can test if this is correct:

    ;; remove from an empty node (removed nothing)
    (remove-max-bst '())                      ; ==> ()
    ;; remove the only value
    (remove-max-bst '(() 5 ()))               ; ==> ()
    ;; remove the highest value
    (remove-max-bst '(() 5 (() 7 ())))        ; ==> (() 5 ())
    ;; same, with a left child
    (remove-max-bst '(() 5 ((() 6 ()) 7 ()))) ; ==> (() 5 (() 6 ()))
    
    0 讨论(0)
提交回复
热议问题