Binary Search Tree To List Scheme

此生再无相见时 提交于 2019-12-25 08:13:49

问题


I am having trouble understanding how to take in a BST and convert it into a list without using append or any advanced techniques. 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.

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.


回答1:


So imagine you have a binary tree with the values (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.

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.

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




回答2:


The short answer to this question is: you're right, you need append. The good news is, (if you're doing this for an assignment), you can easily implement your own append. If you're not doing this as part of an assignment... just use append directly!



来源:https://stackoverflow.com/questions/40443548/binary-search-tree-to-list-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!