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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
addfunction:If you insert something into an empty tree (Case #1), you just create a leaf directly:
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:
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.