简体   繁体   English

球拍 - 产生二叉树中的操作数

[英]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.我的尝试是检查参数是否为数字,如果是,则将总数加 1。

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该函数产生 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 .您的答案非常接近:您只需要修复基本情况,当我们达到一个数字时,我们应该加零:而不是一个:我们正在计算operators的数量,而不是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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