简体   繁体   中英

Binary trees in racket

Hi the problem is I want to see if a binary tree is N

We call binary trees, where N be the number of numbers that will contain the list of all nodes. For example this is a binary tree 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:

  • The parameter is named arbol , but in your code you're referring to it as list (which by the way, is a built-in function). This is what's causing the error reported
  • There's no need to use list-ref for accessing the first element of a list, use car instead
  • You misunderstood how a cond expression works. 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
  • First you must verify the type of the first element in the list, otherwise you run the risk of applying a list function over a number, which will result in an error
  • Finally, it'll be easier to help you if you post the code in English. I can understand Spanish :P , but most people here won't.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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