Imagine an arithmetic expression such as (+ 1 (* 2 (- 3 5))) being thought of as a tree-like structure with numbers at the leaves and operator symbols at the interior nodes like below:
+
/ \
1 *
/ \
2 -
/ \
3 5
I have these functions already defined to access certain parts of the tree:
;; returns tree node
(define (operator lst)
(cadr lst))
;; returns left tree
(define (left-op lst)
(car lst))
;; returns right tree
(define (right-op lst)
(cddr lst))
I am trying to write 3 functions preorder, inorder, and postorder that return a list of the tree traversed in the order they were encountered
I know how the tree traversal works from previous java programming but am having trouble coding this
ex for above:
(preorder '(+ 1 (* 2 (- 3 5)))) => (+ 1 * 2 - 3 5)
Your implementation of trees is not quite right, you need to represent a leaf (a number in the examples) as another tree with null left and right subtrees. Also, it’s useful having a
make-tree“constructor”. Let’s go step-by-step – first, a correct abstraction for representing trees:Now for the traversals. I’ll help you with the first one,
preorder:The tree in the question would look like this:
Use it like this:
The other two traversals are very similar, just rearrange the three arguments for
appendin the correct order for each case – I’ll let that as an exercise for the reader.