1

I have the following type:

data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)

now I want to create a function that gives the highest value leaf in the tree. But I am stuck, because I don't know how to get the two following trees of a given tree.

For example I have a tree a that looks like this: let a = Branch (Leaf 10) (Leaf 2)

How do I read the Leaf with value 10 in another function?

1
  • 3
    Maybe you should try first with the maximum of a plain list instead of a tree. It is the same approach, known as pattern matching together with recursion. Both data structures have exactly two constructors. See function sum' here in LYAH for example. Commented Jan 23, 2022 at 16:24

2 Answers 2

7

When dealing with recursion, you need to keep in mind a base case.

For:

data Tree = Branch (Tree) (Tree) | Leaf Int deriving(Show)

Your base case (no recursion) is Leaf Int. The maximum value of a leaf is very simply the value held by that leaf.

maxTree :: Tree -> Int
maxTree (Leaf n) = n

Now, how do you deal with a Branch? What is a Branch? It's basically two more Trees.

Consider a very simple Tree:

   Branch
    /  \
   /    \
  /      \
Leaf 1   Leaf 4

The max value is obviously 4. Why? Because the maxTree computation on the right branch was bigger than the maxTree calculation on the left branch.

Consider a more complex Tree:

   Branch
    /  \
   /    \
  /      \
Leaf 1   Branch
          / \
         /   \
        /     \
     Branch   Leaf 8
      / \
     /   \
    /     \
  Leaf 3  Leaf 9

The answer is obviously 9. How do we know this? Well, maxTree tells us the maximum value of Leaf 1 is 1. Each Branch's max value is computed by figuring out the maximum value of the left and right branches. If we call maxTree recursively on each Branch eventually we compare 3 to 9. Clearly 9 is bigger. Now we're comparing 9 to 8. 9 is again bigger. And then 9 to 1, and 9 wins out again.

Now you just need to translate that into code.

maxTree :: Tree -> Int
maxTree (Leaf n) = n
maxTree (Branch left right) = ...

Binary Search Tree

Note that all of this becomes much easier if we're not just talking about a binary tree, but a binary search tree with a strict ordering invariant where the contents of the left branch are always less than the contents of the right branch.

maxBSTree :: BSTree -> Int
maxBSTree (Leaf n) = n
maxBSTree (Branch _ right) = maxBSTree right
Sign up to request clarification or add additional context in comments.

Comments

6

A typical skeleton looks like this:

maxTree :: Tree -> Int
maxTree (Branch x y) = {- TODO -}
maxTree (Leaf n) = {- TODO -}

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.