0

I'm trying to write code that if given a tree, will go through the tree and return the minimum value in that tree, if the tree is empty, it will return val. What I have right now compiles but will not run. Any help?

minValue :: Ord a => a -> BTree a -> a
minValue val Empty = val
minValue val (BNode v left Empty) = minimum [minValue v left]
minValue val (BNode v Empty right) = minimum [minValue v right]
minValue val (BNode v left right) = minimum ([minValue v left]++[minValue v right])
6
  • 3
    Are the elements of the tree ordered, as in a binary search tree? In any case, you should not need to use lists or minimum to do this. In the second and third equation they're superfluous anyway—the minimum of a one-element list is the list's one element. Commented Apr 2, 2015 at 20:56
  • The tree is ordered, yes. Commented Apr 2, 2015 at 21:00
  • 2
    Also: I just tried your function and it has this bug: minValue 17 (BNode 22 Empty Empty) == 22 Commented Apr 2, 2015 at 21:08
  • As per @LuisCasillas' comment: the formulation of this function is a little odd. You probably want to remove the first parameter. Using a Maybe a return type may help you cope with Empty trees. Then, at a higher level, you can determine what a reasonable "default" value should be. Commented Apr 2, 2015 at 21:21
  • 1
    If the tree is a binary search tree, the minimum value is located is the leftmost leaf. Commented Apr 2, 2015 at 21:28

1 Answer 1

2

I'm assuming that BTree is defined as

data BTree a = Empty | BNode a (BTree a) (BTree a) deriving (Eq, Show)

Although for future reference please include data type definitions in your question.

The key to the solution here is that the minimum of a node is the minimum of its value and the mins of each branch:

minValue :: Ord a => a -> BTree a -> a
minValue val Empty = val
minValue val (BNode v left right) =
    let leftMin = minValue val left
        rightMin = minValue val right
    in ???

Instead of worrying if the left or right is Empty, just trust the recursion to handle it. If left is Empty, then minValue val left will just be val, and similarly for right. Then you have 4 values in scope that you want to determine the minimum of, val, v, leftMin, and rightMin. How might you do that?

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

Comments

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.