在lisp中构建二进制树

时间:2015-10-27 20:28:44

标签: lisp binary-search-tree

我尝试构建二叉树是lisp。该功能应该这样做

(buildBST  ‘(6 9 2 1 7))  -> (6  (2 (1) ()) (9 (7) ())) 

我们到目前为止的代码将继续返回错误

> 7 nil arguments should be of type real

这是我们的代码

(defun buildBst (lis)
    (cond 
        ((null lis) 0)
        ((atom lis) lis)
        (t (if ( >(car lis)(car(cdr lis)))
                (buildBst( cdr lis))
                (buildBst(cdr lis))))))

1 个答案:

答案 0 :(得分:1)

最好的方法是制作插入功能:

(defun tree-insert-element (tree element)
  (cond ((tree-null-p tree) 
         (make-tree element nil nil))
        ((< (tree-value tree) element) 
         (make-tree (tree-value tree)
                    (tree-left tree)
                    (tree-insert-element (tree-right tree) element)))
        (t 
         (make-tree (tree-value tree)
                    (tree-insert-element (tree-left tree) element)
                    (tree-right tree)))))

因此,当你想插入一大堆时,你可以这样做:

(defun tree-insert-list (tree list)
  (reduce #'tree-insert-element list :initial-value tree))

当然,您需要定义插入函数使用的函数,因为我真的不关心您选择如何建模树。从预期结果来看,我猜make-tree可能只包装list*,但这不是制作树的唯一方法!