1

The type is defined as

data BST = MakeNode BST String BST
          | Empty

I'm trying to add a new leaf to the tree, but I don't really understand how to do it with recursion.

the function is set up like this

add :: String -> BST -> BST
2
  • 1
    Your definition of BST won't work. I think you mean data BST = MakeNode String BST BST | Empty, right? Commented Mar 8, 2012 at 17:32
  • yeah, that was a typo. thanks Commented Mar 8, 2012 at 17:36

1 Answer 1

2

The advantage of using binary trees is that you only need to look at the "current part" of the tree to know where to insert the node.

So, let's define the add function:

add :: String -> BST -> BST

If you insert something into an empty tree (Case #1), you just create a leaf directly:

add s Empty = MakeNode Empty s Empty

If you want to insert something into a node (Case #2), you have to decide which sub-node to insert the value in. You use comparisons to do this test:

add s t@(MakeNode l p r) -- left, pivot, right
  | s > p     = Node l p (add s r) -- Insert into right subtree
  | s < p     = Node (add s l) p r -- Insert into left subtree
  | otherwise = t -- The tree already contains the value, so just return it

Note that this will not rebalance the binary tree. Binary tree rebalancing algorithms can be very complicated and will require a lot of code. So, if you insert a sorted list into the binary tree (e.g. ["a", "b", "c", "d"]), it will become very unbalanced, but such cases are very uncommon in practice.

Sign up to request clarification or add additional context in comments.

5 Comments

@dflemstr could you explain the @ symbol quickly?
The @ symbol creates a name for the whole pattern to the right of it. So, if I do t @ (MakeNode l p r), it's like saying let t = MakeNode l p r in in the code that follows, except that the program won't create a new MakeNode; it will just reuse the old one.
okay, so its makes it so you can either use the the whole BST by using t, and use the pattern by using (MakeNode l p r), basically?
Yes, you could describe it like that.
okay, thanks alot. I was trying to do something like that yesterday I a didn't know how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.