我想返回一個樹(不一定是二叉樹)的節點列表訪問inorder。例如:(a(b)(c(d)(e))),b - 左子樹,(c(d)(e)) - 右邊-subtree,一個 - 根。 結果應該是:b,a,d,c,e遍歷樹LISP
這是我的代碼,但我總是看到「堆棧溢出」錯誤。有人可以幫幫我嗎?
;return left-subtree
(defun left-tree(tree)
(cond
((null tree) NIL)
((not (listp tree)) NIL)
(t (car (cdr tree)))
)
)
;return right-tree
(defun right-tree(tree)
(cond
((null tree) NIL)
((not (listp tree)) NIL)
(t (cdr (cdr tree)))
)
)
;perform inorder
(defun inorder(tree)
(if (not (list-length tree)) 0
(append
(inorder (left-tree tree))
(list (car tree))
(inorder (right-tree tree))
)
)
)
什麼是'(NOT(名單長樹))'的目的是什麼? 「不」的數字總是假的。 –
樹遍歷的順序通常是前序(root,left,right);後序(左,右,根);並按順序(左,右,右)。我知道你張貼了一個輸出的例子,但當你有兩個以上的孩子時,「順序」意味着什麼?例如,如果你有樹(a(b)(c)(d)),那麼按順序遍歷應該是什麼? a b a c a d? –
另外一個問題是,當你想要一個扁平列表時,你在'inorder'的每個評估中創建一個新列表。 [Common Lisp:符號計算的簡潔介紹](http://www.cs.cmu.edu/~dst/LispBook/)中有關'car/cdr遞歸'的部分可能對您有所幫助。 – Pascal