I have this tree[1]:

(tree
 '(game A B)
 (tree '(game A C) '() (tree '(game C B) '() (tree '(game B A) '() '())))
 (tree '(game B C) '() (tree '(game C A) '() (tree '(game A B) '() '()))))

This is how I'd like to print it out:

;; (game A B) --> (game A C) -->  end
;; (game A B) --> (game A C) --> (game C B) -->  end
;; (game A B) --> (game A C) --> (game C B) --> (game B A) --> end
;; (game A B) --> (game B C) -->  end
;; (game A B) --> (game B C) --> (game C A) -->  end
;; (game A B) --> (game B C) --> (game C A) --> (game A B) --> end

You see, some branches have no left or right nodes.  In such cases,
I'd like to avoid going down the tree, otherwise I end up displaying
two different paths as the same path.

To do that, I had to put a second base case in the function below.
(So I'm calling displayln in two different places.)  It looks ugly and
I wonder how you would do it.  Would you do it differently?

(define (print-tree acc-str tree)
  (cond [(empty? tree) (displayln (string-append acc-str " end"))]
        ;; avoid going down the tree if both branches are empty
        [(and (empty? (tree-left tree))
              (empty? (tree-right tree)))
         (displayln (string-append acc-str (format "~a " (tree-root
tree)) "--> end"))]
        [else
         (print-tree
               (string-append acc-str (format "~a " (tree-root tree)) "--> ")
               (tree-left tree))
         (print-tree
          (string-append acc-str (format "~a " (tree-root tree)) "--> ")
          (tree-right tree))]))

Thank you!

(*) Footnotes

[1] This tree represents the following tourney.  A matches B.  If A
wins, it matches C.  If B wins, B matches C.  In general, a winning
player matches the third player (who is not playing).  If a player
wins two games in a row, the tourney is over.  Also, if 4 matches in a
row take place, the tourney is over.

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to