1

嗨,我是 Racket 的新手,将它用于二叉树结构。

使用以下结构

(define-struct human(age hight))

我创建了以下对象/变量/人

(define James(make-human 10 50))

如果我在二叉树结构中有一个节点

(define-struct node (left human right))

鉴于詹姆斯在节点内,我如何将不同对象的高度(比如迈克尔)与詹姆斯进行比较,例如:

 (define (insert-human-into-tree human node)
  (cond
    [(empty? node)(make-node empty human empty)]
    [(<= human-hight( **node-human-hight**))

我需要知道如何访问节点内的人类对象的 hight 字段(node-human-hight)。

4

2 回答 2

3

使用结构中的访问器过程,例如:

(define-struct human(age hight))
(define james (make-human 10 50))
(define-struct node (left human right))

(define anode (make-node null james null))
; access the human in the node, and then the height of that human
(human-hight (node-human anode))
=> 50

...它的拼写是“高度”,而不是“高度”。因此,要回答这个问题,比较将如下所示:

(<= (human-hight (node-human node)) (human-hight human))
于 2013-05-14T20:29:28.580 回答
1

insert-human-into-tree将需要更多的比较才能实际插入一个新节点。它看起来像这样(这也回答了你的主要问题):

(define (insert-human-into-tree human node)
  (if (empty? node)
      (make-node empty human empty)
      (let ((other (node-human node)))
        (cond ((< (human-height other) (human-height human))
               (insert-human-into-tree human (node-left node)))    ; go left
              ((> (human-height other) (human-height human))
               (insert-human-into-tree human (node-right node)))   ; go right
              (else ;; same height
                ...)))))

这会让你开始。

于 2013-05-14T21:43:52.127 回答