我想在Racket中创建一个二叉搜索树。树的结构如下所示:
(define-struct tree-node (left right root))
现在我想在树中添加这些数字:
(define ex-list (list 1 4 6 2 7 8))
我的插入程序代码:
(define (insert-in-tree list tree)
(cond
[(empty? tree)
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node empty empty (first list)))]
[(empty? list)
tree]
[(> (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node
(tree-node-left tree)
(make-tree-node empty empty (first list))
(tree-node-root tree)))]
[(< (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node
(make-tree-node empty empty (first list))
(tree-node-right tree)
(tree-node-root tree)))]
[(= (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list))) tree)]
[else tree]))
我对代码的看法是什么:
我的问题:当树只是 1 时,程序会添加4作为新根元素添加到右侧。当我然后添加6它将替换4但它应该为6添加一个新节点。
我知道这个版本的代码不起作用,因为在列表只是一个元素的情况下,这段代码将不起作用。
代码级别为中级学生
答案 0 :(得分:1)
此:
(cons (second list) (rest (rest list)))
是一种非常奇怪的写(rest list)
的方式,如果list
比两个元素短,也可以确保错误。
更改它,我们注意到它仍然会导致空列表出错;所以处理此可能性的条款必须移到顶部
(define (insert-in-tree list tree)
(cond
[ (empty? list)
tree ]
[ (empty? tree)
(insert-in-tree (rest list)
(make-tree-node empty empty (first list))) ]
[ (> (first list) (tree-node-root tree))
(insert-in-tree (rest list)
(make-tree-node
........
至少现在它不会导致错误:
> (insert-in-tree (list 1 2 3) empty)
(make-tree-node '() (make-tree-node '() '() 3) 1)
> (insert-in-tree (list 1 2 3 4 3 5) empty)
(make-tree-node '() (make-tree-node '() '() 5) 1)
>
但是抓住这一切,你的方法都是错的。您的代码混合了两个基本上独立的问题:枚举列表元素,并将元素插入树中。
分开您的疑虑。每项任务都应该有自己的专用功能。以这种方式编写将使您可以轻松地通过在列表枚举函数中进行小的更改来组合这两个任务,以利用插入函数。
插入函数将实现比较逻辑,并使用... 插入函数,如果需要插入分支,因为分支是树,他们自己。