简体   繁体   中英

tree traversal inorder LISP

I am trying to return the list of nodes of a tree(not necessarily binary tree) accessed inorder.

The tree is represented as a list with sublists, for example: (a (b) (c (d) (e))), b - left-subtree, (c (d) (e)) - right-subtree, a -root. The result should be: b,a,d,c,e

This is my code, but i always seem to get the "stack overflow" error. Can someone please help me?

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

The infinite recursion is caused by the fact that a number is never false-y.
Replace (not (list-length tree)) with (null tree) .
(That is, recurse over structure, not over size.)

Once you fix this, you will get a type error due to your base case result in inorder - it should be nil , not 0 .

Once you fix that , you will find another problem:

CL-USER> (inorder '(a (b) (c (d) (e))))
(B A (C (D) (E)))

This is far from correct.

If you look at the result of right-tree , it's not actually what you claim it should be:

CL-USER> (right-tree '(a (b) (c (d) (e))))
((C (D) (E)))

As you can see, this is a one-element list with the right subtree in it, not the right subtree.
(Testing each function in isolation is a good idea, especially if you're certain that they're correct.)

The root is the first list item (the car ), the left subtree is the second (the car of the cdr - cadr ), and the right subtree is the third item (the car of the cdr of the cdr - caddr ), not the rest of the list starting at the third item as you wrote.
You need to extract the subtree:

(defun right-tree(tree)
  (cond
    ((null tree) NIL)
    ((not (listp tree)) NIL)
    (t (caddr tree))))

CL-USER> (inorder '(a (b) (c (d) (e))))
(B A D C E)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM