简体   繁体   English

在方案中将值插入二进制搜索树

[英]Inserting a value into a binary search tree in scheme

I'm attempting to create a function that inserts a value into a binary search tree. 我正在尝试创建一个将值插入二进制搜索树的函数。 The conditions within the function seem to work correctly, but I'm not quite sure how to actually insert the value once I reach the null point in the list where it should go. 函数中的条件似乎可以正常工作,但是我不确定在到达列表中的空点后该如何实际插入该值。

bst-element refers to another function I have checking if the value already exists in the tree, since the tree should have no duplicates. bst-element表示我要检查树中是否已经存在该值的另一​​个函数,因为树应该没有重复项。

(define (bst-insert item bst-tree)
  (cond ((bst-element? item bst-tree)bst-tree)
        ((null? bst-tree) ??? )
        ((< item (bst-value bst-tree))(bst-insert item (bst-left bst-tree)))
        ((> item (bst-value bst-tree))(bst-insert item (bst-right bst-tree)))))

If you want to insert a value in a tree in a functional way, that is without side-effects, you cannot assume that there is something to do only when you reach the leaf in which you should insert the new value. 如果要以功能性的方式在树中插入值,而没有副作用,则不能假定当到达要在其中插入新值的叶子时才需要做某事。 Rather, you should rebuild the tree while you visit it, so that at the end the result is the new tree with item insert in the right position. 相反,您应该在访问树时对其进行重建 ,以使最终结果是新树的插入位置正确。

Since you do not show how the tree is implemented, I suppose that an empty tree is represented as '() , and that there exists a function (make-bst item left right) to build a tree with a certain item , a left subtree, and a right subtree. 由于您没有显示树的实现方式,因此我假设一个空树表示为'() ,并且存在一个函数(make-bst item left right)来构建带有某个itemleft子树)的树,以及right子树。 Under these assumptions, here is a possible solution: 在这些假设下,这是一个可能的解决方案:

(define (bst-insert item bst-tree)
  (cond ((null? bst-tree) (make-bst item '() '()))
        ((= (bst-value bst-tree) item) bst-tree)
        ((< item (bst-value bst-tree))
         (make-bst (bst-value bst-tree)
                   (bst-insert item (bst-left bst-tree))
                   (bst-right bst-tree)))
        (else (make-bst (bst-value bst-tree)
                        (bst-left bst-tree)
                        (bst-insert item (bst-right bst-tree))))))

Note that the check if the item is already present is made inside this function, without the need of duplicating the work with another function. 请注意,检查该项目是否已经存在是在此函数内部进行的,而无需将工作与另一个函数重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM