Lisp - Recursive Traversal of Tree



Lisp has strong support for Recursive call and tree traversal is best implemented using recursive function calls. In this chapter, we'll discuss how to represent a binary tree in LISP and traversing it using recursive calls.

Representing a Binary Tree

Binary Trees are general trees in which the root node can only hold up to maximum 2 subtrees: left subtree and right subtree.

Binary Tree

In Lisp, we can represent the tree using list of lists. We'll using following tree as example:

(defvar my-tree '(A (B (D nil nil) (E nil nil)) (C (F nil nil) (G nil nil))))

; print the tree
(print my-tree)

Output

When you execute the code, it returns the following result −

(A (B (D NIL NIL) (E NIL NIL)) (C (F NIL NIL) (G NIL NIL)))

Here

  • Value− Node value is represented by the first element of the list.

  • Left Subtree− Second element,the list represents the left subtree.

  • Right Subtree− Third element,the list represents the right subtree.

  • nil− nil represents an empty subtree.

main.lisp

(defun tree-traverse (tree)
   "Recursively traverses a tree and print value."
   (cond
      ((null tree) nil) ; Base case: if tree is empty
      ((atom tree) (print tree)) ; Base case: leaf node as atom
      (t ; Recursive case: in case of list (subtree)
         (tree-traverse (car tree)) ; Traverse left subtree
         (tree-traverse (cdr tree))))) ; Traverse right subtree

; define the tree
(defvar my-tree '(A (B (D nil nil) (E nil nil)) (C (F nil nil) (G nil nil))))

; print the tree elements
(tree-traverse my-tree)

Output

When you execute the code, it returns the following result −

(A (B (D NIL NIL) (E NIL NIL)) (C (F NIL NIL) (G NIL NIL)))

Explanation

  • defun− defines the function.

  • cond− is used to compare elements of the tree.

  • null tree− is used to check it tree in empty.

  • atom tree− is used to check it tree node is a leaf node. Element is printed in case of leaf node.

  • car tree− returns the first element of the tree.

  • cdr tree− returns the rest of the elements of the tree as subtree.

  • tree-traverse(car tree)&minus traverses the left tree recursively.

  • tree-traverse(cdr tree)&minus traverses the right tree recursively.

Recursion is the key here to traverse the subtrees using recursive function call.

Advertisements