Lisp - Inorder Traversal of Tree



In Lisp, we represent a tree as list of lists. In this chapter, we're discussing how to do an inorder traversal of a binary tree.

In-Order Traversal

In this traversal method, the left subtree is visited first, then the root and later the right subtree. We should always remember that every node may represent a subtree itself.

In Order Traversal Binary Tree

We start from A, and following in-order traversal, we move to its left subtree B.B is also traversed in-order. The process goes on until all the nodes are visited. The output of in-order traversal of this tree will be −

D → B → E → A → F → C → G

Algorithm

Until all nodes are traversed −

Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

Tree Representation

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.

Example - In Order Traversal of a Binary Tree

main.lisp

; define inorder traversal function
(defun inorder-traversal (tree)
   (when tree
      (inorder-traversal (cadr tree)) ; Traverse left tree
      (print (car tree)) ; Visit the node and print the value
      (inorder-traversal (caddr tree)))) ; Traverse right tree

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

(inorder-traversal my-tree)

Output

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

D 
B 
E 
A 
F 
C 
G 

Explanation

  • defun− defines the function.

  • when− executes block when tree is not nil.

  • cadr tree− equivalent to (car (cdr tree)) returns the second element as left subtree.

  • car tree&minus returns the first element as root and print it.

  • caddr tree− equivalent to (car (cdr (cdr tree))) returns the third element as right subtree.

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

Advertisements