I am a complete newbie with Lisp so go easy on me. Im trying to implement a binary search tree into an array and be able to output it in order. I have this array where index 1 is the root and 2*i is the left child, 2*i + 1 is the right child:
#(NIL 30 15 50 10 20 NIL 70 3 NIL 17 NIL NIL NIL NIL 80 NIL NIL NIL NIL NIL NIL
NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL
NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL
NIL NIL NIL)
And Im sending it to this function to extract the in order output from the tree:
(defun inOrder (tree rootIndex)
(setq leftI (* rootIndex 2))
(setq rightI (+ leftI 1))
(if (aref tree leftI)
(inOrder tree leftI))
(format t "~D," (aref tree rootIndex))
(if (aref tree rightI)
(inOrder tree rightI)))
The expected output should be 3,10,15,17,20,30,50,70,80, but I get 3,10,15,30. It appears that the code after the format is not getting executed. If anyone can help me that would be greatly appreciated.
You are using leftI
and rightI
as absolute variables, so the recursion does not work as intended. Instead, define them as local variables with a let*
:
(defun inOrder (tree rootIndex)
(let* ((leftI (* rootIndex 2))
(rightI (+ leftI 1)))
(if (aref tree leftI)
(inOrder tree leftI))
(format t "~D," (aref tree rootIndex))
(if (aref tree rightI)
(inOrder tree rightI))))