简体   繁体   中英

implementing binary search tree in scheme

Functions in scheme/racket. Working on a few functions using a binary search tree. I have already defined helper functions to be:

;; returns value of node
(define (value node)
    (if (null? node) '()
        (car node)))

;; returns left subtree of node
(define (left node)
    (if (null? node) '()
    (cadr node)))

;; returns right subtree of node
(define (right node)
    (if (null? node) '()
    (caddr node)))

and I am trying to write a function size that takes a tree as a parameter and returns the number of non-null nodes in the given tree

It seems you're very close. Try this (untested):

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

Though, personally, I would much rather prefer to use #f as the null value, rather than '() . In that case, use not instead of null? in the first line.

Just an alternative!! You could have used structs, which would reduce the work of writing the three functions...

(struct node (val left right) #:transparent)
(struct null-tree ())

and directly write the above function using in-built functions for a struct, ie a predicate and parameter accessors.

(define (size tree)
  (if (null-tree? tree) 0
    (+ 1 (size (left tree)) (size (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