【发布时间】:2018-02-24 17:57:41
【问题描述】:
以前,我在一个家庭作业中完成了一个在方案中实现二叉搜索树的练习,现在我正在尝试将此代码转换为堆。我正在努力寻找将新元素插入堆的正确位置。在二叉搜索树中,我们只需使用谓词在树中导航,比较向左或向右的每个节点。
(define (bst-insert bst f x)
(cond ((bst-is-empty? bst) (bst-create x
(bst-create-empty)
(bst-create-empty)))
((f x (bst-root bst)) (bst-create (bst-root bst)
(bst-insert (bst-left bst) f x)
(bst-right bst)))
(else (bst-create (bst-root bst)
(bst-left bst)
(bst-insert (bst-right bst) f x)))))
这里 f 是我们的谓词函数。但是对于一个堆,我们应该在下一个可用位置插入。为了找到下一个位置,我是否缺少技巧?
编辑:
(define heap-create list)
(define (heap-create-empty) '())
(define heap-root car)
(define heap-left cadr)
(define heap-right caddr)
(define heap-is-empty? null?)
(define (heap-insert h f x)
(if (null? h) (heap-create x (heap-create-empty) (heap-create-empty))
(let ((h (heap-root h)))
(if (f x h) (heap-create x (heap-right h) (heap-insert (heap-left h) f h))
(heap-create h (heap-right h) (heap-insert (heap-left) f x))))))
(define (list->heap xs f)
(heap-insert (heap-create) xs f))
所以我已经在上面发布了我当前的代码,我想我更接近了,但是我收到的输出是 '(#<procedure:<> () ()) 当调用 (list->heap '(3 1 5 9 8 2 7 4 6) <) 时出现了问题
【问题讨论】: