简体   繁体   中英

racket: maximum height of a binary tree

I'm trying to create a code in racket that will find the maximum distance in a binary search tree from the root to a leaf.

I've seen this done in C++ but am having trouble translating it to racket. I've managed to calculate all the nodes in a tree, but haven't managed to make any calculate paths individually.

Any advice? I've seen templates and all of that, but still haven't managed to make one work.

This is what I've tried so far

 (define-struct node (left right))

 (define (maxdepth tree)
    (cond 
          [(null? tree) 0]
          [ (> (size (node-left tree)) (size (node-right tree)))
                   (maxdepth (node-left tree))]
[else (maxdepth (node-right tree))]))


  (define (size tree)
      (if (null? tree) 0
         (+ 1 (size (node-left tree)) (size (node-right tree)))))

We only need one function - maxdepth , and we only have to find the max of each subtree plus the height of the current node:

(define (maxdepth tree)
  (cond 
    [(null? tree) 0]
    [else (+ 1 (max (maxdepth (node-left  tree))
                    (maxdepth (node-right tree))))]))

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