I need help in 3 tasks. I'm really new in Haskell and functional programming.
data Tree = Node Int Tree Tree | Nil
Define with help of the function
collapsecollapse :: Tree -> [Int] collapse Nil = [] collapse (Node x y z) = (collapse y) ++ [x] ++ (collapse z)a Haskell-Function
check :: Tree -> Boolwhich checks if the Tree is a binary search tree.
I test that with a tree and get 2 4 7 8 10 | 5 6 10 12. Here you can see that all values to the middle are sorted, but I don't know how i should code that.
Define a Haskell-Function
insert :: Int -> Tree -> Treewhich adds the Integer Value to the Tree and return also a binary search tree.
Define with the function
insert(2) a Haskell-Functionmerge :: Tree -> Tree -> Treewhich merges two trees to another binary search tree.
Alright, I won't answer all these questions, but I can provide some help.
If we actually try collapse on a tree that looks like this
a
/ \
/ \
b c
/ \ / \
d e f g
we'd get [d, b, e, a, f, c, g]. Notice that if an element appears "to the left" of an element in the tree, it is "to the left of" that element in our flat list. We know that if an element, a, is to the left of an element, c, in a binary search tree then a < c. So we just need to check that this property holds for our list.
Inserting an element in a tree. We have 4 cases to deal with
insert newVal (Node treeVal left right) | newVal < treeVal = <1>
| newVal > treeVal = <2>
| otherwise = <3>
insert newVal Nil = <4>
where <1> is inserting into a Node with a value greater than the one in the node. <2> is the opposite: the node has a greater value than the new value. In 3 they are equal and in 4 we are inserting into Nil, the base case. You can pretty much directly translate the definition of a binary search tree to fill in the holes here.
Since we aren't trying to have a balanced binary tree, if we have 2 trees, A and B. All we have to do is find the location where the root of B would be inserted and stick the whole tree there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With