简体   繁体   English

二进制搜索树到列表方案

[英]Binary Search Tree To List Scheme

I am having trouble understanding how to take in a BST and convert it into a list without using append or any advanced techniques. 我在理解如何使用BST并将其转换为列表而不使用附加或任何高级技术时遇到麻烦。 For example, you are given a BST with each node having a number and a name (sorted by string smallest to largest) and you want to output a list, in order, of the items in that BST with a value of 3 or something along these lines. 例如,为您提供了一个BST,每个节点都有一个数字和一个名称(按从最小到最大的字符串排序),并且您想要按顺序输出该BST中值为3或类似值的项目的列表。这些线。

I understand this can be done recursively but I think my biggest problem with understanding this has to do with the splitting of the left and right nodes, because you are using recursion on both of these but then you somehow have to put them together in the final list. 我知道可以递归地完成此操作,但我认为了解此问题的最大问题与左右节点的拆分有关,因为您在这两个节点上都使用了递归,但是您必须以某种方式将它们放到最后清单。

Any help in understanding this is appreciated, thank you in advance. 感谢您对理解此问题的任何帮助,在此先感谢您。

So imagine you have a binary tree with the values (1 2 3 4) . 因此,假设您有一棵具有值(1 2 3 4)的二叉树。 You know that you cannot cons 1 unles you already have (2 3 4) etc. so actually you need to accumulate them in reverse. 你知道你不能cons 1 unles你已经有(2 3 4)等,所以实际上你需要积累他们相反。

In a binary search tree in order traversal is left side, this value, right side så making a list using cons would be doing right side, this node, left side. 在二叉搜索树中,顺序遍历是左侧,此值,右侧将使用cons列出,将在右侧,此节点,左侧。

(define (tree->list tree)
  (let rec ((tree tree) (lst '()))
    (if (tree-null? tree)
        lst
        (rec (tree-left tree)
             (cons (tree-value tree)
                   (rec (tree-right tree) lst))))))

It might not look like it does the right side first, but remember that a procedure needs to have evaluated it's arguments before itself can be applied. 它可能看起来不像首先执行右侧操作,但请记住,过程必须先评估其参数,然后才能应用。

How you have implemented the data structure for your tree is not mentioned so I just made some procedures up. 没有提到如何为树实现数据结构,因此我只做了一些程序。 It really doesn't matter for the end result. 最终结果真的无关紧要。

The short answer to this question is: you're right, you need append . 这个问题的简短答案是:您是对的,您需要append The good news is, (if you're doing this for an assignment), you can easily implement your own append . 好消息是,(如果您要执行分配任务),则可以轻松实现自己的append If you're not doing this as part of an assignment... just use append directly! 如果您不是在分配作业中执行此操作,请直接使用append

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

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