Lisp - Postorder Traversal of Tree



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

Post-Order Traversal

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

Post Order Traversal Binary Tree

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

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

Algorithm

Until all nodes are traversed −

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

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

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

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

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

  • nil− nil represents an empty subtree.

Example - Post Order Traversal of a Binary Tree

main.lisp

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

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

(postorder-traversal my-tree)

Output

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

D 
E 
B 
F 
G 
C 
A

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.

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

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

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

Advertisements