Lisp - Preorder Traversal of Tree



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

Pre-Order Traversal

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

Pre Order Traversal Binary Tree

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

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

Algorithm

Until all nodes are traversed −

Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
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 - Pre Order Traversal of a Binary Tree

main.lisp

; define preorder traversal function
(defun preorder-traversal (tree)
   (when tree
      (print (car tree)) ; Visit the node and print the value
      (preorder-traversal (cadr tree)) ; Traverse left tree
      (preorder-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))))

(preorder-traversal my-tree)

Output

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

A 
B 
D 
E 
C 
F 
G 

Explanation

  • defun− defines the function.

  • when− executes block when tree is not nil.

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

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

  • 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