简体   繁体   中英

racket - produce the number of operations in a binary tree

I'm trying to write a function that consumes a binary tree and produces the total number of operations in it. My attempt was checking if the argument is a number, if it is, then add 1 to the total.

Can someone help me with my code?

(define-struct binode (op arg1 arg2))
(define (count-ops bin-exp)
  (cond
    [(number? bin-exp) 1]
    [(binode? bin-exp)
     (+ (count-ops (binode-arg1 bin-exp))
        (count-ops (binode-arg2 bin-exp)))]))

Test:

(check-expect (count-ops (make-binode ‘+ 4 (make-binode ‘- 5 (make-bin ode ‘+ 3 2)))) 3)

Instead of the expected result the function produces 4

Your answer is so close: You just have to fix the base case, when we reach a number we should add zero: not one: we're counting the number of operators , not the number of operands .

Conversely, in the recursive case we have to add one: if we reach the recursive step it's because we're at an operator, and those are the ones we want to count. This is what I mean:

(define-struct binode (op arg1 arg2))

(define (count-ops bin-exp)
  (cond
    [(number? bin-exp) 0]
    [(binode? bin-exp)
     (+ 1 (count-ops (binode-arg1 bin-exp))
          (count-ops (binode-arg2 bin-exp)))]
    [else (error "Invalid input:" bin-exp)]))

It works as expected:

(count-ops (make-binode '+ 4 (make-binode '- 5 (make-binode '+ 3 2))))
=> 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM