简体   繁体   中英

Binary tree inorder traversal Racket

I am trying to write the algorithm for inorder traversal for a binary tree using RACKET/DR. RACKET

 (define (print-records node number)
      (cond
      [(not (empty? node-left))(print-records (node-left node) number )]
      *Do This before moving to next IF clause*
      [(not (empty? node-right))(print-records(node-right node) number)]

      ))

I am trying to follow the following algorithm

InOrder(node)
if node is null return
InOrder(node.left)
Print(node)
InOrder(node.Right)

My problem is that through COND I can execute one expression and it will skip the rest. I tried to add two expressions under one it did not work either eg ((a)(b)). I also tried to make a helper procedure but that did not work either.

You're using cond in a wrong way. Notice that you have to recursively traverse the left part of the tree, then visit the current node and then recursively traverse the right part of the tree - they're not mutually exclusive alternatives, the three steps need to be performed in precisely that order. Try something like this instead:

(define (print-records node number)
  (unless (empty? (node-left node))
    (print-records (node-left node) number))
  (print (node-value node)) ; replace this line with the actual printing code
  (unless (empty? (node-right node))
    (print-records (node-right node) number)))

Some explanations:

  • (unless <condition> <body>) is just shorthand for (cond ((not <condition>) <body>)) .
  • The real work of the traversal is done between the two recursive calls, in this case I wrote (print (node-value node)) as an example, replace that line with the actual printing code for the current node's value.
  • It's not clear what do you intend to do with the number parameter, as it is it's just being passed around, unused.

Walking a binary-tree is a very general operation. You can make a general procedure and then specialize it with the function to apply to each node.

(define (walker node function)
  (unless (empty? node)
    (walker (node-left  node) function)
    (function node)
    (walker (node-right node) function)))

Note: it is nice to check for empty? at the beginning of the function.

(define (print-records node number)
  (walker node (compose print node-value)))  ; ignore number, it seems.

You could also work this as:

(define (walking-with function)
  (letrec ((walker (lambda (node)
                     (unless (empty? node)
                       (walker (node-left  node))
                       (function node)
                       (walker (node-right node))))))
     walker))
(define print-records-for (walking-with (compose print node-value)))
(print-records-for node)
> ...

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