August 19, 2024

P61 - Count the leaves of a binary tree

A leaf is a node with no successors. Write a function count-leaves to count them.

(count-leaves tree) returns the number of leaves of binary tree tree

lisp

(defun count-leaves (tree)
  (cond
   ((null tree) 0)
   ((and (null (second tree)) (null (third tree))) 1)
   (t (+ (count-leaves (second tree)) (count-leaves (third tree))))
   )
  )
Be first to comment
Leave a reply