Note that there are some explanatory texts on larger screens.

plurals
  1. POFind the deepest element of a Binary Tree in SML
    primarykey
    data
    text
    <p>This is a homework question.</p> <p>My question is simple: Write a function btree_deepest of type 'a btree -> 'a list that returns the list of the deepest elements of the tree. If the tree is empty, then deepest should return []. If there are multiple elements of the input tree at the same maximal depth, then deepest should return a list containing those deepest elements, ordered according to a preorder traversal. Your function must use the provided btree_reduce function and must not be recursive.</p> <p>Here is my code:</p> <pre><code>(* Binary tree datatype. *) datatype 'a btree = Leaf | Node of 'a btree * 'a * 'a btree (* A reduction function. *) (* btree_reduce : ('b * 'a * 'b -&gt; 'b) -&gt; 'b -&gt; 'a tree -&gt; 'b) *) fun btree_reduce f b bt = case bt of Leaf =&gt; b | Node (l, x, r) =&gt; f (btree_reduce f b l, x, btree_reduce f b r) (* btree_size : 'a btree -&gt; int *) fun btree_size bt = btree_reduce (fn(x,a,y) =&gt; x+a+y) 1 bt (* btree_height : 'a btree -&gt; int *) fun btree_height bt = btree_reduce (fn(l,n,r) =&gt; Int.max(l, r)+1) 0 bt </code></pre> <p>I know that I have to create a function to pass to btree_reduce to build the list of deepest elements and that is where I am faltering.</p> <p>If I were allowed to use recursion then I would just compare the heights of the left and right node then recurse on whichever branch was higher (or recurse on both if they were the same height) then return the current element when the height is zero and throw these elements into a list. </p> <p>I think I just need a push in the right direction to get started...</p> <p>Thanks!</p> <p>Update:</p> <p>Here is an attempt at a solution that doesn't compile:</p> <pre><code>fun btree_deepest bt = let val (returnMe, height) = btree_reduce (fn((left_ele, left_dep),n,(right_ele, right_dep)) =&gt; if left_dep = right_dep then if left_dep = 0 then ([n], 1) else ([left_ele::right_ele], left_dep + 1) else if left_dep &gt; right_dep then (left_ele, left_dep+1) else (right_ele, right_dep+1) ) ([], 0) bt in returnMe end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload