SHARE
TWEET

Untitled

a guest Nov 21st, 2019 107 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #lang racket
  2.  (require racket/trace)
  3. (define (tree? t)
  4.   (or (null? t)
  5.       (and (list? t)
  6.            (= (length t) 3))
  7.            (tree? (cadr t))
  8.            (tree? (caddr t))))
  9. (define empty-tree '())
  10. (define (make-tree root left right) (list root left right))      ; не искаме просто (define make-tree list) - защо?
  11. (define (make-leaf root) (make-tree root empty-tree empty-tree)) ; за удобство
  12. (define root-tree car)
  13. (define left-tree cadr)
  14. (define right-tree caddr)
  15. (define empty-tree? null?)
  16.  
  17. (define t
  18.   (make-tree 10
  19.              (make-tree 7
  20.                         (make-leaf 12)
  21.                         (make-leaf 2))
  22.              (make-tree 3
  23.                         (make-tree 4
  24.                                    (make-leaf 1)
  25.                                    (make-leaf 2))
  26.                         empty-tree)))
  27.  
  28. (define (tree-sum tree)
  29.   (cond
  30.     ((empty? tree) 0)
  31.     (else (+ (root-tree tree) (tree-sum (left-tree tree)) (tree-sum (right-tree tree))))
  32.   )
  33. )
  34.  
  35. (define (tree-level level tree)
  36.  (cond
  37.    ((null? tree) '())
  38.    ((= level 0) (list (root-tree tree)))
  39.    (else (append (tree-level (- level 1) (left-tree tree)) (tree-level (- level 1) (right-tree tree))))
  40.   )
  41.   )
  42.  
  43. (define (all-levels tree)
  44.   (define (all-levels-iter tree lvl)
  45.     (if (empty? (tree-level lvl tree)) '()
  46.      (cons (tree-level lvl tree) (all-levels-iter tree (+ 1 lvl))))
  47.     )
  48. (all-levels-iter tree 0)
  49. )
  50.  
  51. (define (tree-map f t)
  52.   (cond
  53.     ((empty? t ) '())
  54.     (else (list  (f (root-tree t))  (tree-map f (left-tree t) ) (tree-map f (right-tree t))))))
  55.  
  56. (define (tree->list t)
  57.   (cond
  58.     ((empty? t) '())
  59.     (else (append  (tree->list (left-tree t)) (list (car t))  (tree->list (right-tree t)))))
  60.   )
  61.  
  62. ;Да се напише функция (bst-insert val t), която вмъква стойността val в двоичното наредено дърво t.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top