簡體   English   中英

R5RS 方案,哈夫曼樹函數

[英]R5RS Scheme, Huffman tree function

目標是創建一個霍夫曼樹(如果您不知道它是什么,請使用 google),其輸出不包含值的權重,僅包含由占位符“內部”保存的葉子中的值。 我創建了一個看起來正確的工作函數,除了每個“內部”之外,還有不應該存在的額外空列表。 如果有人可以查看代碼並看到我的錯誤或優化它的方法,我將不勝感激。

(define (build-huffman lst)
  (let ((x (insert-list-of-pairs lst '())))
    (define (huffman-help heap)
      (if (null? (remove-min heap))
          heap
          (let ((rx (remove-min heap)))
            (if (list? (h-min heap))
                (huffman-help (insert (cons (make-internal-node (value (h-min heap))
                                                                (value (h-min rx)))
                                            (+ (weight (h-min rx))
                                               (weight (h-min heap))))
                                       (remove-min rx)))
                (huffman-help (insert (cons (make-internal-node (create-heap (value (h-min heap)) '() '())
                                                                (create-heap (value (h-min rx)) '() '()))
                                          (+ (weight (h-min rx))
                                             (weight (h-min heap))))
                                      (remove-min rx)))))))
  (car (car (huffman-help x)))))

一些函數是不言自明的,我知道問題出在這段代碼中,而不是任何其他函數。

(insert-list-of-pairs) - 獲取對列表,例如。 “((no . 7) (yes . 4)),”並將其插入到堆中。

(insert) - 將一對插入堆中。

(remove-min) - 刪除堆的最小值。

(make-internal-node 0-tree 1-tree) -> (list 'internal 0-tree 1-tree)

你找過模式嗎? 在我看來,您的代碼在沒有更多相同的節點要添加到樹之后添加了空列表。 它看起來像作業,所以我無法給你答案,但請查看你的代碼,看看你是否可以在添加最后一個相同重量的節點后讓它停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM