问题
I am trying to add a new node to the tree. The following are my definitions and function type:
(define-struct (Some T)
([value : T]))
(define-type (Option T)
(U 'None (Some T)))
(define-type BST (U 'E Nd))
(define-struct Nd
([root : Integer]
[lsub : BST]
[rsub : BST]))
(: insert : Integer BST -> BST)
;; insert an item into a tree
;; note: do not insert duplicate items
(define (insert n x)
(match x
('E 'E)
((Nd ro ls rs)
(cond
((= (size x) 1) (Nd ro (Nd n 'E 'E) 'E))
(else
(Nd ro ls rs))))))
Insert is the insert that will insert the node into the tree.
The following is the command that I will give:
(insert 10 (Nd 1 (Nd 2 (Nd 4 'E 'E) (Nd 5 'E 'E)) (Nd 3 (Nd 6 'E 'E) (Nd 7 'E 'E))))
And it should insert ten into the tree. However, I am learning independently at home and I have NO idea what to do. Please help. Thank you so much!
回答1:
You're missing the recursion, and your base case is wrong.
Inserting in an empty tree creates a tree with one node.
Inserting in a non-empty BST has three cases:
- If the item is the same as in this node, return the tree unchanged
- If the item is smaller than this node, insert in the left subtree
- Otherwise, insert in the right subtree
Something like
(define (insert n x)
(match x
('E (Nd n 'E 'E))
((Nd ro ls rs)
(cond
((= n ro) x)
((< n ro) (Nd ro (insert n ls) rs))
(else (Nd ro ls (insert n rs)))))))
The tree you're aiming to insert in isn't a BST though, so this won't work.
Your tree has the following structure:
1
/\
2 3
/\ /\
4 5 6 7
A search tree with those elements would look like this:
4
/\
2 6
/\ /\
1 3 5 7
which is
(Nd 4 (Nd 2 (Nd 1 'E 'E) (Nd 3 'E 'E)) (Nd 6 (Nd 5 'E 'E) (Nd 7 'E 'E)))
来源:https://stackoverflow.com/questions/40519825/insert-node-into-a-tree-racket