#lang racket
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (leaf? object)
(eq? (car object) 'leaf))
(define (symbol-leaf x) (cadr x))
(define (weight-leaf x) (caddr x))
(define (make-code-tree left right)
(list left
right
(append (symbols left) (symbols right))
(+ (weight left) (weight right))))
(define (left-branch tree) (car tree))
(define (right-branch tree) (cadr tree))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (decode bits tree)
(define (decode-l bits current-branch)
(if (null? bits)
'()
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-l (cdr bits) tree))
(decode-l (cdr bits) next-branch)))))
(decode-l bits tree))
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit -- CHOSSE-BRANCH" bit))))
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))
(define (make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair)
(cadr pair))
(make-leaf-set (cdr pairs))))))
(define (encode message tree)
(if (null? message)
'()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
(define (encode-symbol message tree)
(cond ((leaf? tree) null)
((element-of-set? message (symbols (left-branch tree)))
(cons 0 (encode-symbol message (left-branch tree))))
((element-of-set? message (symbols (right-branch tree)))
(cons 1 (encode-symbol message (right-branch tree))))
(else (error "bad bit -- CHOSSE-BRANCH" message))))
(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(define (successive-merge set)
(if (= (length set) 1) (car set)
(successive-merge (adjoin-set (make-code-tree (car set) (cadr set)) (cddr set)))))
(define n5-pairs '((A 16) (B 8) (C 4) (D 2) (E 1)))
(define n10-pairs '((A 512) (B 256) (C 128) (D 64) (E 32) (F 16) (G 8) (H 4) (I 2) (J 1)))
(define n5-tree (generate-huffman-tree n5-pairs))
(define n10-tree (generate-huffman-tree n10-pairs))
(define n5-max '(A A A A A))
(define n5-min '(E E E E E))
(define n10-max '(A A A A A A A A A A))
(define n10-min '(J J J J J J J J J J))
(length (encode n5-max n5-tree))
(length (encode n5-min n5-tree))
(length (encode n10-max n10-tree))
(length (encode n10-min n10-tree))
运行结果
5
20
10
90
如果是有n个符号进行编码,那么,最小的编码长度位n,最大的编码长度为n*(n-1),因为最低频率出现的符号,在树的最低端,树一共有n-1层,所以他的编码长度是n-1,所以一共就是n*(n-1)的长度