[英]Binary trees in racket
Hi the problem is I want to see if a binary tree is N 嗨,问题是我想看看二叉树是否为N
We call binary trees, where N be the number of numbers that will contain the list of all nodes. 我们称二叉树,其中N是将包含所有节点列表的数字数。 For example this is a binary tree 2:
例如,这是一个二叉树2:
'((1 2) ((7 10) ((2 4) null null)) ((6 8) ((10 13) null null) null))
And this is a binary tree 1: 这是一个二叉树:
'(2- (7- (2 null null) (6 (5 null null) (11 null null))) (5 null (9 (4 null null) null)))
I have this code: 我有以下代码:
(define (abN? arbol N) (
cond
[(= (length (list-ref list 0)) N) "Arbol Binario N" "No es un arbol binario N" ]
[(= (number? (car list)) N) "Arbol Binario 1" "No es un arbol binario 1" ]
)
)
Then put this in the console: 然后将其放在控制台中:
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
and give me this error 给我这个错误
car: contract violation
expected: pair?
given: #<procedure:list>
What I have been mistaken? 我误会了什么?
Thank you. 谢谢。
There are several mistakes in your code, try this: 您的代码中有几个错误,请尝试以下操作:
(define (abN? arbol N)
(cond
[(number? (car arbol))
(if (= N 1)
"Arbol Binario 1"
"No es un arbol binario 1")]
[(list? (car arbol))
(if (= (length (car arbol)) N)
"Arbol Binario N"
"No es un arbol binario N")]
[else (error "Dato de entrada incorrecto")]))
Explanation: 说明:
arbol
, but in your code you're referring to it as list
(which by the way, is a built-in function). arbol
,但是在您的代码中您将其称为list
(顺便说一句,它是一个内置函数)。 This is what's causing the error reported list-ref
for accessing the first element of a list, use car
instead list-ref
来访问list-ref
的第一个元素,而是使用car
cond
expression works. cond
表达式的工作原理。 Each condition evaluates to the last value of the expressions that follow it, if you need to test for further conditions you have to use an if
or another cond
inside, you seem to believe that each condition has an implicit if-else
condition, and that's not correct if
或另一个cond
,您似乎认为每个条件都有一个隐式if-else
条件,那就是不正确 It works as expected for the possible inputs: 对于可能的输入,它按预期方式工作:
(abN? '(1 ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 1)
=> "Arbol Binario 1"
(abN? '(1 ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
=> "No es un arbol binario 1"
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
=> "Arbol Binario N"
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 3)
=> "No es un arbol binario N"
(abN? '("bogus" ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 3)
=> Unknown input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.