我想在 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 添加一个新节点。
我知道这个版本的代码不起作用,因为在列表只是一个元素的情况下,这个代码不起作用。
代码级别为中级学生