Binary trees in scheme

三世轮回 提交于 2019-12-22 18:46:10

问题


How would I count how many nodes a tree has?

;;; A Binary is one of:
;;; - Number
;;; - (make-node BT BT)


(define-struct node (left right))

(define tree1 (make-node (make-node 10 9)
(make-node 3
(make-node 1 5))))

(define (how-many? nd)
  (cond
    [(number? nd)....]
    [(node? n)
     (..... (how-many? (node-left nd))
             (how-many? (node-right nd)))]))

so for tree1 I should get

 (check-expect (how-many? tree1) 5)

I think I got the template right. If it's a number, you should return 1. But if it's a node, what type of function should I put in the dotted lines?


回答1:


This is somewhat similar to how you'd process a list. The difference? that now you'll go to the "left" and to the "right" of each node, instead of going just to the "rest". Other than that, the same ideas apply:

(define (how-many? nd)
  (cond
    [(number? nd) <???>] ; if it's a leaf, then how many numbers does it have?
    [(node? nd)
     (<???> (how-many? (node-left nd)) ; how do we combine the results?
            (how-many? (node-right nd)))]))

You got the base case right, as I can see in the question. The recursive case is simple! remember, how did we combine the results when we were adding the elements in a list? here's the same thing, it's just that we combine the results from the left and from the right subtrees.



来源:https://stackoverflow.com/questions/19986977/binary-trees-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!