简体   繁体   中英

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

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.

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!

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