Blob


1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "htdp-advanced-reader.ss" "lang")((modname |31.3|) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp")))))
4 (define-struct node (left right))
6 ;A binary-tree (bt) is either
7 ;1. empty or
8 ;2. (make-node l r)
9 ;where l,r are binary-trees (bt).
10 ;
11 ;height-1 : bt -> number
12 ;Determines the height (depth) of a binary tree using structural recursion.
14 (define (height-1 abt)
15 (cond
16 [(empty? abt) 0]
17 [else (+ (max (height-1 (node-left abt))
18 (height-1 (node-right abt)))
19 1)]))
21 ;height-2 : bt -> number
22 ;Determines the height (depth) of a binary tree using an accumulator.
24 (define (height-2 abt)
25 (local ;; the accumulator represents the number of nodes passed in going from abt to bt0
26 ((define (height-aux bt0 accumulator)
27 (cond
28 [(empty? bt0) accumulator]
29 [else (max (height-aux (node-left bt0) (+ 1 accumulator))
30 (height-aux (node-right bt0) (+ 1 accumulator)))])))
31 (height-aux abt 0)))
33 (define bt1 (make-node
34 (make-node
35 empty
36 (make-node empty empty))
37 empty))
38 (height-1 bt1)
39 (height-2 bt1)