简体   繁体   中英

Tree sorting function in Scheme

Im struggling with this problem for over 2 days now and still somehow I cannot solve it. I have to write a function in SCHEME that takes a list in a tree and displays items in sorted order.

The way I define trees is '(6 (left... ) (right...))

My function to choose a tree:

(define (tree-sort tree)
 (cond  ((null? tree) '())
    ((> (car tree) (cadr tree))
     (tree-sort (cadr tree)))
    (else
     (tree-sort (caddr tree))))
)

So I guess I should also have a function that sorts the most indepth list? I really dont get it and this is the last time I will ever have to deal with scheme. I have never used stackoverflow so please excuse me if the formating is wrong.

Kindly thank you!

Now that you clarified that the tree is already sorted, then you're looking for an in-order traversal of the tree, which returns a sorted list of the elements - I'm assuming that you're interested in a list as the output, because of the base case shown in the question. Try something like this:

(define (tree-sort tree)
  (if (empty-tree? tree)
      '()
      (append (tree-sort (left-subtree tree))
              (list (value tree))
              (tree-sort (right-subtree tree)))))

Use the appropriate procedures for testing if the tree is empty and for accessing each node's value, left and right subtrees. The above procedure will return a sorted list with the trees' values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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