Frage

I'm trying to build a tree in racket. For the moment I have build a "static" tree just for testing the insert method. It runs down the tree to the correct position but it fails to insert the new node.

This is the tree:

(define bst
  (make-node 4
             (make-node 2 empty 
                        (make-node 3 empty empty))
             (make-node 5 empty
                        (make-node 11 empty 
                                   (make-node 12 empty
                                   (make-node 13 empty empty))))))

The insert method (I left all the debugging prints so it's easy to see what happens and the the tree is correct):

(define (insert ABB val)
  (cond[(empty? ABB)(make-node val empty empty)]
       [(< val (node-val ABB))
        (cond
          [(empty? (node-left ABB))
             (printf "\nEntered here\n")
             (node-left ABB)(make-node val empty empty) ; this doesn't work
             (printf "\nABB node-left: ~a" (node-left ABB))
             (printf "\nABB node-left: ~a" (node-val ABB))]
             [else 
              (printf "\nABB node-left (else): ~a" (node-left ABB))
              (insert ((node-left ABB) val))]
             )
        ]
       [(> val (node-val ABB))
        (cond
          [(empty? (node-right ABB))
             (node-left ABB)(make-node val empty empty) ; this doesn't work
             (printf "\nABB node-val (empty): ~a" (node-val ABB))
             (printf "\nEntered here 2\n")
             (node-right ABB)(make-node val empty empty)
             (printf "\nABB node-r:")])]
         [else 
           (printf "\nABB node-val (else): ~a" (node-val ABB))
           (printf "\nABB node-right (else): ~a" (node-right ABB))
           (insert (node-right ABB) val)])
        ]
       )
  )

After that I'm trying to insert 17:

(insert bst 17)

Printing the tree as a list:

(define (tree->list tree)
  (if (empty? tree)
      empty
      (append (tree->list (node-right tree))
              (cons (node-val tree)
                    (tree->list (node-left tree))))))


(printf "\n\nPrinting tree as list: \n")
(tree->list bst)

Output:

Printing tree as list: 
'(13 12 11 5 4 3 2)

'17' doesn't show up. I can't assign the new node to the left/right field of the current node (ABB points to it). What's the problem here?

Keine korrekte Lösung

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top