我會很感激這個練習。 練習310.按順序設計功能。它消耗一棵二叉樹,併產生樹中所有ssn數字的序列,因爲它們在查看樹圖時從左到右顯示。 練習310.「如何設計程序」
我的解決方案只是將每個左節點與節點下的節點顛倒過來,然後訪問正確的節點。雖然順序是正確的,但答案並不是正確的格式。這是我的代碼:
(define-struct no-info [])
(define NONE (make-no-info))
(define-struct node [ssn name left right])
; A BinaryTree (short: BT) is one of:
; – NONE
; – (make-node Number Symbol BT BT)
(define nine9 (make-node 99 "nine9" NONE NONE))
(define one0 (make-node 10 "one0" NONE NONE))
(define two4 (make-node 24 "two4" NONE NONE))
(define one5 (make-node 15 "one5" one0 two4))
(define seven7 (make-node 77 "seven7" NONE NONE))
(define nine5 (make-node 95 "nine5" NONE nine9))
(define two9 (make-node 29 "two9" one5 one8))
(define eight9 (make-node 89 "eight9" seven7 nine5))
(define six3 (make-node 63 "six3" two9 eight9))
; BT -> list
; produce the sequence of ssn numbers from left to right
(define (inorder bt)
(cond
[(no-info? bt) '()]
[else (append (reverse (cons (node-ssn bt) (list (inorder (node-left bt)))))
(inorder (node-right bt)))]))
這是結果,當我運行(inorder six3)
(名單(名單(名單(名單 '()10)15'()24)29)63(名單「()77) 89'()95'()99)
感謝您的。我應該提到這個問題給出了以下提示:提示使用append,它連接像這樣的列表: (append(list 1 2 3)(list 4)(list 5 6 7)) == (list 1 2 3 4 5 6 7) – user1897830