简体   繁体   English

Scheme中的树排序功能

[英]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. 我必须在SCHEME中编写一个函数,该函数接受树中的列表并按排序顺序显示项目。

The way I define trees is '(6 (left... ) (right...)) 我定义树的方式是'(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. 我从未使用过stackoverflow,因此如果格式错误,请原谅。

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. 上面的过程将返回带有树值的排序列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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