Lisp - Modifying Tree



A tree in LISP is represented using list of lists. First element of the list is the value of then node and rest are children of the tree. For example −

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

Here A is root, B and C are chilren of A and so on.

Basic Functions on Tree

  • car− to get the first element as node value.

  • cdr− to get the subtree, accesses the rest of the list as children.

  • cons− to create a new node or subtree.

  • list− to create a new list or tree.

  • null− to check if tree is empty

  • consp− to check if value is cons cell.

Adding element to a tree

main.lisp

(defun insert-node (tree parent child)
   "Add a new node as child to parent node."
   (if (null tree)
      nil
      (if (eq (car tree) parent)
         (cons (car tree) (cons child (cdr tree)))
         (cons (car tree) (mapcar #'(lambda (subtree) (insert-node subtree parent child)) (cdr tree)))
      )
   )
)

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

; print original tree
(print my-tree)

; add a node to the tree
(setf my-tree (insert-node my-tree 'B '(G H)))

; print updated tree
(print my-tree)

Output

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

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

Deleting element from a tree

main.lisp

(defun delete-node (tree node)
   "Deletes a node from the tree."
   (if (null tree)
      nil
      (if (eq (car tree) node)
         nil
         (cons (car tree) (mapcar #'(lambda (subtree) (delete-node subtree node)) (cdr tree)))
      )
   )
)

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

; print original tree
(print my-tree)

; remove node from the tree
(setf my-tree (delete-node my-tree 'D))

; print updated tree
(print my-tree)

Output

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

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

Searching element of a tree

main.lisp

(defun search-node (tree node)
   "Search a node in the tree."
   (if (null tree)
      nil
      (if (eq (car tree) node)
         t
         (some #'(lambda (subtree) (search-node subtree node)) (cdr tree))
      )
   )
)

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

; print original tree
(print my-tree)

; search existing node in tree; T
(print(search-node my-tree 'D))

; search non-existing node in tree; NIL
(print(search-node my-tree 'G))

Output

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

(A (B (D) (E)) (C (F))) 
T 
NIL 
Advertisements