So I was asked to make a Binary Tree in Haskell taking as input a list of Integers. Below is my code. My problem is that the last element of the list is not getting inserted in the Tree. For example [1,2,3,4] it only inserts to the tree until “3” and 4 is not inserted in the Tree.
data ArbolBinario a = Node a (ArbolBinario a) (ArbolBinario a) | EmptyNode
deriving(Show)
insert(x) EmptyNode= insert(tail x) (Node (head x) EmptyNode EmptyNode)
insert(x) (Node e izq der)
|x == [] = EmptyNode --I added this line to fix the Prelude.Head Empty List error, after I added this line the last element started to be ignored and not inserted in the tree
|head x == e = (Node e izq der)
|head x < e = (Node e (insert x izq) der)
|head x > e = (Node e izq (insert x der))
Any ideas on whats going on here? Help is much appreciated
To solve this problem, I have used another function
and to construct a binary tree, you need to call
buildtreefunction. the problem is that you need to reverse the list first. So,treewill do the job.UPDATE
you can avoid using another function, this way:
however, it is not as efficient as using foldl or the other way, the only good thing about it is using only one function to do everything, no reverse is required.