2013-05-14 65 views
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)内所述的场HIGHT。

回答

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 

...它的拼写 “高度”,而不是 “HIGHT”。因此,要回答这个问题,比较是这样的:

(<= (human-hight (node-human node)) (human-hight human)) 
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 
       ...))))) 

这会让你开始。