I'm using Haskell for this class I'm in and I have to make an insertion of in a binary search tree with recursion. Here is my tree definition:
data Tree = Leaf Int | Branch Tree Tree
An example would be:
tree1 = Branch ((Branch (Leaf 2) (Leaf 4)) (Branch (Leaf 6) (Leaf 10)))
My insert function should get a Tree and an Int and return a Tree:
insert :: Tree -> Int -> Tree
I just cant understand how to go about this problem.
edit: I know pattern matching. Here is what i thought.
insert :: Tree -> Int -> Tree
insert (Leaf i) j = if (i > j) than Branch (Leaf j) (Leaf i)
else Leaf i
insert (Branch l r) j = Branch (insert l j) (insert r j)
I know this is wrong. It gets the value inserted more than once if there are two or more numbers greater than j.
edit2: So I followed @Willem Van Onsem suggestion and got this:
infimum :: Tree -> Int
infimum (Leaf i) = i;
infimum (Branch l r) = infimum r
insert :: Tree -> Int -> Tree
insert (Leaf i) j = if (j > i) then Branch (Leaf i) (Leaf j)
else Branch (Leaf j) (Leaf i)
insert (Branch l r) j = if (j > (infimum l)) then Branch l (insert r j)
else Branch (insert l j) r
It works. I guess it cant be done with one function only.
X
are smaller (greater) than the value atX
. – chepner