make tree in scheme

Posted by ??? on Stack Overflow See other posts from Stack Overflow or by ???
Published on 2012-08-27T22:48:17Z Indexed on 2012/08/28 3:38 UTC
Read the original article Hit count: 240

Filed under:
|
|
|
|
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right) (list entry left right))

(define (mktree order items_list)
  (cond ((= (length items_list) 1)
         (make-tree (car items_list) '() '()))
        (else 
         (insert2 order (car items_list) (mktree order (cdr items_list))))))

(define (insert2 order x t)
  (cond ((null? t) (make-tree x '() '()))
      ((order x  (entry t))
       (make-tree (entry t) (insert2 order x (left-branch t)) (right-branch t)))
      ((order  (entry t) x )
       (make-tree (entry t) (left-branch t) (insert2 order x (right-branch t))))
      (else t)))

The result is:

(mktree (lambda (x y) (< x y)) (list 7 3 5 1 9 11))
(11 (9 (1 () (5 (3 () ()) (7 () ()))) ()) ())

But I'm trying to get:

(7 (3 (1 () ()) (5 () ())) (9 () (11 () ())))

Where is the problem?

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about recursion