Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
1.3 kB
2
Indexable
Never
; =====================================================================
;; A3d
;; =====================================================================

;; Additional helper functions
;; Counts number of nodes given tree t
(define (count-nodes t)
  (cond
    [(empty? t) 0]
    [else (add1
           (+
            (count-nodes (node-left t))
            (count-nodes (node-right t))
            )
           )]
    )
  )

;; Checks if a number is a power of two
(define (power-of-two? n)
  (cond
    [(<= n 0) false]
    [else
     (integer? (log n 2))
     ]
    )
  )


(define (tree-grow-min n)
  (cond
    [(empty? n) (make-node empty empty)]
    [(<
      (count-nodes (node-left n)) (count-nodes (node-right n))
      )
     (make-node
      (tree-grow-min (node-left n))
      (node-right n)
      )
     ]
    [else (make-node (node-left n) (tree-grow-min (node-right n)))]
    )
  )

(define (tree-shrink-min n)
  (cond
    [(empty? n) n]
    [(= 1 (count-nodes n)) empty]
    [(and (power-of-two? (count-nodes n)) (empty? (node-left n))) (node-right n)]
    [(and (power-of-two? (count-nodes n)) (empty? (node-right n))) (node-left n)]
    [(< (count-nodes (left-node n)) (count-nodes (right-node n))) ()]
    )
  )
Leave a Comment