Question

5c Please code in language Ocaml .In each of the three parts in this problem, you...

5c

Please code in language Ocaml

.In each of the three parts in this problem, you will get full credit if you use foldT and define at most one helper function.

(c) TODO: Define a function height : ’a binTree -> int which returns an integer representing the height of the tree. Trees consisting of only a leaf have height 0

starter code:

type 'a binTree =
| Leaf
| Node of 'a * ('a binTree) * ('a binTree)

let height (t : 'a binTree) : int = (* your work here *) 0

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The tree definition here is that a node is either a Leaf or consists of left and right nodes. The Node constructor is made of 3 arguments, namely the value, left subtree and right subtree.

The height function just uses the recursive definition of the height of a tree, if it's a Leaf return 0, else it returns the maximum height amongst the left and right subtree plus 1.


Note: The Ocaml linter on my sublime text converts '|' to '/' in function definitions. Any '/' that appears in purple is actually '|'

Code Snippet.

type 'a binTree =
   | Leaf
   | Node of 'a * ('a binTree) * ('a binTree)

let rec height t =
   match t with
   | Leaf-> (0)
   | Node(v, l,r) -> 1 + max (height l) (height r)

Add a comment
Know the answer?
Add Answer to:
5c Please code in language Ocaml .In each of the three parts in this problem, you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT