Carter Wilson
Carter Wilson

Reputation: 69

How can I find the height of a tree in scheme?

Define a Scheme procedure (tree-height t) that calculates the height of a non-empty tree t

(define (height tree)
  (if (null? tree)
      0
      (max (height (caddr tree)))))

'(5(1(8)(2(1)(9)))(10)(4(9)))

Should return 4

Upvotes: 1

Views: 1105

Answers (1)

Jodast
Jodast

Reputation: 1299

You're right, you forgot to add 1 to the answer, but you also forgot to take the max of the cadr and the caddr, you just found the max of the caddr. You could have a tree whose left branch is larger than the right branch, but your program would return the height of the right branch, and incorrect answer. This code should solve your problem.

(define (height tree)
  (if (null? tree)
        0
        (+ 1 (max (height (cadr tree)) 
                  (height (caddr tree))))))

Upvotes: 2

Related Questions