【发布时间】:2012-09-15 17:21:31
【问题描述】:
所以我基本上想打印bst的..这里有一点细节
提供一个函数 (printbst t),该函数打印由 bst.rkt 提供的 BST 构造的 BST,格式如下:
-BST中的每个节点都应该打印在单独的行上;
-左子树应该打印在根之后;
-右子树应该打印在根之前;
- 键值应该缩进 2d 个空格,其中 d 是它的深度,或与根的距离。也就是说,根不应缩进,其子树中的键应为 2 个空格,其子树中的键应为 4 个空格,依此类推。
例如,包含 {1,2,3,4,5,6} 的完整树会这样打印:
6
5
4
3
2
1
请注意,如果您顺时针旋转输出并将每个节点连接到它的子树,您就会得到树的传统图形表示。不要使用突变。
这是我目前所拥有的:
#lang racket
;;Note: struct-out exports all functions associated with the structure
(provide (struct-out BST))
(define-struct BST (key left right) #:transparent)
(define (depth key bst)
(cond
[(or (empty? bst) (= key (BST-key bst))) 0]
[else (+ 1 (depth key (BST-right bst)) (depth key (BST-left bst)))]))
(define (indent int)
(cond
[(= int 0) ""]
[else " " (indent (sub1 int))]))
(define (printbst t)
(cond
[(empty? t) (newline)]
[(and (empty? (BST-right t)) (empty? (BST-left t)))
(printf "~a~a" (indent (depth (BST-key t) t)) (BST-key t))]))
我的 printbst 只打印一个带有一个节点的树 .... 我有一个想法,但它涉及突变,我不能使用 :( ..... 有什么建议吗?我应该改变解决问题的方法吗一起来?
【问题讨论】:
标签: printing scheme racket binary-search-tree