;;; Problem description: Define a function to compute the number of nodes ;;; with an only child in a binary tree. These are nodes with only one child, ;;; whether the latter is a left or right child. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Basically, there are four cases to account for: ;;; ;;; 1) A null tree ;;; 2) A tree with no children ;;; 3) A tree with 2 children ;;; 4) A tree with 1 child ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (count-partial-nodes tree) ;;; For a null tree, just return 0 (cond ((null? tree) 0) ;;; If the tree has no children, return 0 ((atom? tree) 0) ;;; If the tree has two children, do not count the current node, but sum up the number of partial nodes in the two children ((and (null? (left-branch tree)) (null? (right-branch tree))) (+ 0 (count-partial-nodes (left-branch tree)) (count-partial-nodes (right-branch tree)))) ;;; Otherwise, the node has one child, so you will count the current node, and sum up the number of partial nodes in the two children. Note that even though one of the children is null, that will be alright in the recursive call because of the null tree check above. (else (+ 1 (count-partial-nodes (left-branch tree)) (count-partial-nodes (right-branch tree))))))