August 26, 2024

P61A - Collect the leaves of a binary tree in a list.

A leaf is a node with no successors. Write a methodleafListto collect them in a list.

> E = #node{value = "a", leftNode = #node{value = "b"}, rightNode = #node{ value = "c" }}.
    
    p61a:leafList(E).                                                                        
   ["b","c"]

erlang

% Count the leaves of a binary tree

module (p61a).
-include ("node.hrl").
-export ([leafList / 1]).

leafList (#node { value = V, leftNode = L, rightNode = R }) - >
    case [L, R] of
        [null, null] - > [V];
        [null, RR] - > leafList (RR);
        [LL, null] - > leafList (LL);
        [LL, RR] - > leafList (LL) ++ leafList (RR)
    than.
Be first to comment
Leave a reply