I want to create a binary search tree in Racket. The structure for tree looks like this:
(define-struct tree-node (left right root))
Now I want to add these numbers in the tree:
(define ex-list (list 1 4 6 2 7 8))
My Code for the insert procedure:
(define (insert-in-tree list tree)
(cond
[(empty? tree)
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node empty empty (first list)))]
[(empty? list)
tree]
[(> (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node
(tree-node-left tree)
(make-tree-node empty empty (first list))
(tree-node-root tree)))]
[(< (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list)))
(make-tree-node
(make-tree-node empty empty (first list))
(tree-node-right tree)
(tree-node-root tree)))]
[(= (first list) (tree-node-root tree))
(insert-in-tree (cons (second list) (rest (rest list))) tree)]
[else tree]))
What is my idea of the code:
- First it checks wether the given tree is empty, if so a new one will be created
- When the first number in the list is bigger than the root of the tree, it will be added on the right hand side, for smaller on the left side
- Equal numbers will be ignored
My Problem: When the tree is just the 1 and the procedure adds the 4 its added as a new root element in the right side. When I then add the 6 it will replace the 4 but it should add a new node for the 6.
I know that this version of code is not working because in the case when the list is just one element this code won't work.
The level of code is Intermediate Student