I implemented a function for inserting nodes in a binary tree.
Tree node is a list of the form (left-node key right-node).(insert tree n) is my insert node function, where tree is a list of tree nodes in a binary search tree and I want to add the key value n as a new node.
So, (insert '(((() 4 ()) 5 (() 2 ())) 6 ()) 7) gives the output as (((() 4 ()) 5 (() 2 ())) 6 (() 7 ())).
Now, what I want to do is something like this :
1. Define a list of values.
(define (f) (list '1 `2 `3 `4 `5 ))
2. Loop through the list and enter the values one by one in a tree, starting from an empty tree.
So, when I tried to do step 2, I did the following :
(define x ()) ;; Tree x is initially empty
(insert x 2) ;; This prints (() 2 ())
(insert x 1) ;; This prints (() 1 ()). I want it to be ((() 1 ()) 2 ()).
(insert x 3) ;; This prints (() 3 ()). I want it to be ((() 1 ()) 2 (() 3 ())).
That is where I am stuck.
I provide my insert function below.
(define (left tree) (list-ref tree 0))
(define (value tree) (list-ref tree 1))
(define (right tree) (list-ref tree 2))
(define (insert tree n)
(cond
[( null? tree ) ( list () n () )]
[(< n (cadr tree)) (list (insert (car tree) n) (cadr tree) (caddr tree))]
[(> n (cadr tree)) (list (car tree) (cadr tree) (insert (caddr tree) n))]
[else tree]
)
)
Can someone suggest how I can achieve my intended outputs ?