0

我是一個Lisp的新手,所以對我來說很簡單。我試圖實現一個二進制搜索樹到一個數組,並能夠按順序輸出它。 我有此陣列,其中索引1是根和2 * i是左子,2 * i + 1的是右孩子:函數中的代碼沒有執行

#(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) 

並且Im將它發送到這個函數抽取以便輸出從樹:

(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))) 

預期產量應該是3,10,15,17,20,30,50,70,80,但我得到3,10,15,30。 看起來格式之後的代碼沒有得到執行。如果任何人都可以幫助我,將不勝感激。

+0

請不要在CL中輸入camelcase名稱。默認情況下,閱讀器會提升未轉義的字符。這就是爲什麼你如果在評論中評價''leftU'',你會看到'LEFTU'。 [TLDR符號不區分大小寫] – Baggers

回答

1

您正在使用leftIrightI作爲絕對變量,因此遞歸無法按預期工作。相反,將它們定義爲局部變量: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)))) 
+0

謝謝。工作:) – AllAnimals