Scheme: Remove the maximum from a BST

筅森魡賤 提交于 2021-01-20 12:18:06

问题


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 function (provided bellow) from a BST written in scheme, but I have a hard time grasping the ideas in it. I know the Scheme syntax, however there is a lot of going on in this function and thus I am a bit confused.

(define removemax-BST 
 (lambda (T) 
  (cond ((null? (caddr t)) (cons (cadr t) (car t))
   (else (let ((r (removemax-BST (caddr t))))
    (cons (list (car t) (cadr t) (car r)) (cdr r))))
     )))

Is there a kind soul that can do a step by step explanation of this function for me as if you were explaining to a baby? I genuinely want to understand but my brain cannot fully grasp it.

Thank you.


回答1:


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 ()))


来源:https://stackoverflow.com/questions/49579470/scheme-remove-the-maximum-from-a-bst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!