Lisp - Search Tree



A tree can be searched in many ways based on the type of a tree in LISP and search algorithm. In this chapter, we're discussing commonly used approaches to search a tree.

Representation of Tree

  • Binary Tree - a binary tree is represented as (node left-subtree right-subtree)

  • Generic Tree - a generic tree is represented as (node child1 ... childn)

Example - Binary Tree

(defvar binary-tree '(1 (2 nil (3 nil nil)) (4 (5 nil nil) nil)))

Example - Generic Tree

(defvar general-tree '(A (B (C) (D)) (E (F) (G))))

Using Search on a Binary tree

Following example is showing how to search an element in a binary tree.

main.lisp

; function to search an element while traversing in pre-order
(defun search-tree (tree target)
  (when tree
    (let ((node (car tree))
          (children (cdr tree)))
      (if (eql node target)
          t
          (dolist (child children)
            (when (search-tree child target)
              (return t)))))))

; define a binary tree
(defvar binary-tree '(1 (2 nil (3 nil nil)) (4 (5 nil nil) nil)))

(print (search-tree binary-tree 3)) ; Output: T
(terpri)
(print (search-tree binary-tree 6)) ; Output: NIL

Output

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

T 
NIL 

Using Search on a Generic tree

Following example is showing how to search an element in a generic tree.

main.lisp

; function to search an element while traversing in pre-order
(defun search-tree (tree target)
  (when tree
    (let ((node (car tree))
          (children (cdr tree)))
      (if (eql node target)
          t
          (dolist (child children)
            (when (search-tree child target)
              (return t)))))))

; define a generic tree
(defvar general-tree '(A (B (C) (D)) (E (F) (G))))

(print (search-tree general-tree 'G)) ; Output: T
(terpri)
(print (search-tree general-tree 'Z)) ; Output: NIL

Output

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

T 
NIL 

Explanation

  • when tree − checks if tree is not empty

  • node (car tree) − first element of tree is stored in variable node

  • children (cdr tree) − rest elements of tree are stored in variable children

  • eql node target − if element found, t is returned.

  • dolist (child children) − elements of children list are iterated.

  • search-tree child target − search-tree is called recursively on each element. If element found, t is returned.

Advertisements