2

I'm trying to build a binary tree is lisp. The function should do this

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

The code we have so far will keep returning the error

> 7 nil arguments should be of type real

Here's our code

(defun buildBst (lis)
    (cond 
        ((null lis) 0)
        ((atom lis) lis)
        (t (if ( >(car lis)(car(cdr lis)))
                (buildBst( cdr lis))
                (buildBst(cdr lis))))))
4
  • You're not checking for the case where lis only has 1 element. You do (> (car lis) (car (cdr lis)), but if there's only 1 element, (car (cdr lis)) will be NIL. Commented Oct 27, 2015 at 20:31
  • Both alternatives of your if statement do exactly the same thing? Is that really what you want there? Commented Oct 27, 2015 at 20:32
  • You don't seem to be combining the recursive call with what you already have. So the final result won't be a tree, it will just be the result of the innermost recursion. Commented Oct 27, 2015 at 20:33
  • both 'null lis' and 'atom lis' should check for one element Commented Oct 27, 2015 at 20:35

1 Answer 1

2

The best approach would be to make an insert function:

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

Thus when you want to insert a whole bunch you can do this:

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

Of course, you'll need to define the functions the insert function uses as I really don't care how you choose to model a tree. From the look of the expected result I guess make-tree might just wrap list*, but thats not the only way to make a tree!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.