【问题标题】:Inserting a value into a binary search tree in scheme在方案中将值插入二叉搜索树
【发布时间】:2015-11-01 09:21:33
【问题描述】:

我正在尝试创建一个将值插入二叉搜索树的函数。函数中的条件似乎工作正常,但我不太确定一旦我到达列表中它应该去的空点,如何实际插入该值。

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)))))

【问题讨论】:

    标签: tree scheme


    【解决方案1】:

    如果你想以一种功能性的方式在树中插入一个值,即没有副作用,你不能假设只有当你到达你所在的叶子时才有事情要做应该插入新值。相反,您应该在访问树时重建树,这样最后的结果就是新树,其中项目插入在正确的位置。

    由于你没有展示树是如何实现的,我假设一个空树表示为'(),并且存在一个函数(make-bst item left right)来构建一个具有某个item的树,一个@987654324 @ 子树和 right 子树。在这些假设下,这里有一个可能的解决方案:

    (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))))))
    

    请注意,该项目是否已经存在的检查是在此函数中进行的,无需与另一个函数重复工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-24
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多