Lisp - Depth First Traversal of Tree



Depth First Search (DFS) algorithm is a recursive algorithm for searching all the vertices of a tree data structure. In this chapter, we'll discuss how to perform a depth first traversal on a tree in LISP.

Depth First Search (DFS) Algorithm

Depth First Search algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

Depth First Travesal

As in the example given above, DFS algorithm traverses from S to A to D to G to E to B first, then to F and lastly to C. It employs the following rules.

Until all nodes are traversed −

Step 1 − Visit the current node and check for subtree.
Step 2 − Recursively traverse subtree.
Step 3 − If single node, add it to result

Tree Representation

We'll using following tree as example:

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

; print the tree
(print my-tree)

Output

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

(S (A (D (G NIL NIL))) (B (E (G NIL NIL))) (C (F 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.

Example - Depth First Traversal of a Tree

main.lisp

; function to perform depth first traversal
(defun depth-first-traversal (tree)
  (if (null tree) ; if tree is empty, return empty list
      '()
      (append (list (car tree)) ; visit current node
              (if (consp (cdr tree)) ; if the rest is a tree
                  (mapcan #'depth-first-traversal (cdr tree)) ; Traverse each subtree recursively
                  (if (cdr tree) (list (cdr tree)) '()))))) ; only one child, add to result.
                  
; define the tree
(defvar my-tree '(S (A (D (G nil nil)))(B (E (G nil nil)))(C (F nil nil))))

; print the tree elements
(print(depth-first-traversal my-tree))

Output

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

(S A D G B E G C F) 

Explanation

  • defun− defines the function.

  • if (null tree)− executes block when tree is nil to return an empty list.

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

  • cdr tree− returns the rest of the tree

  • consp&minus checks if object is a list

  • mapcan&minus recursively calls the function defined.

Advertisements