简体   繁体   中英

Racket inorder(tree) returns list

I created an inorder function like this:

(define inorder
  (λ (tree) 
            (unless(empty? (node-left tree)) (inorder(node-left tree)))
            (print (node-x tree))
            (unless(empty? (node-right tree)) (inorder(node-right tree)))
  )
)

How can I create a list with all the node-x tree elements instead of printing them. I need my inorder function to return a list of those elements. I tried using an auxiliary function but it didn't work...

You'll need to imagine that (inorder (node-left tree)) and (inorder (node-right tree)) both return a list. How do you take those and this element to make the final result?

The result for an empty tree would be an empty list. That should be your base case:

Thus you need it to look something like this:

(define (inorder tree)
  (if (empty? tree)
      '()
      (append (inorder (node-left tree))
              (list (node-x tree))
              (inorder (node-right tree)))))

A much better version that doesn't use append for each level but places the elements in it's correct position once for each element is this:

(define (tree->list tree)
  (let tree->list ((n tree) (acc '()))
    (if (empty? n)
        acc
        (tree->list
         (node-left n)
         (cons (node-x n)
               (tree->list (node-right n) acc))))))

Slightly harder to understand at first but it performs better on larger trees.

The first step is getting inorder to return a list. Assuming you want a flat list, this means we can take the list returned by inorder for the left sub-tree, the current node, and the right sub-tree, and append each list of those in order to produce a flat list of node values from the very left of your binary tree to the right.

(define inorder
  (λ (tree) 
    (append (inorder(node-left tree))
            (list (node-x tree))
            (inorder(node-right tree)))))

Notice that I make a list of length 1 for the current node, meanwhile the sub-trees will return lists. This skeleton should be enough to wrap your head around how recursion will solve this problem.

Now for the case where we get an empty tree: if we have an empty tree then we should return an empty list since it has no elements to add. This is easy to do using if :

(define inorder
  (λ (tree)
    (if (empty? tree)
        '()
        (append (inorder(node-left tree))
                (list (node-x tree))
                (inorder(node-right tree))))))

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