Function Repository Resource:

ProperLeafCount

Source Notebook

Count the terminal nodes of an expression tree

Contributed by: Bradley Klee

ResourceFunction["ProperLeafCount"][expr]

counts terminal nodes of the tree graph associated with atomistic tree expression expr.

Details

An atomistic tree expression is an expression that does not contain compound heads.

Examples

Basic Examples (1) 

Count leaves of binary trees:

In[1]:=
Union[ResourceFunction["ProperLeafCount"] /@ Groupings[Tuples[{\[FormalA], \[FormalB]}, #], {2}]] & /@ Range[2, 5]
Out[1]=

Properties and Relations (2) 

ProperLeafCount is usually less than LeafCount:

In[2]:=
With[{trees = Groupings[Tuples[{\[FormalA], \[FormalB]}, #], {2}]},
   Thread[
    Union[ResourceFunction["ProperLeafCount"] /@ trees] < Union[LeafCount /@ trees]]
   ] & /@ Range[2, 5]
Out[2]=

In at least one trivial case, ProperLeafCount can equal LeafCount:

In[3]:=
ResourceFunction["ProperLeafCount"][\[FormalA]] == LeafCount[\[FormalB]]
Out[3]=

Possible Issues (1) 

For nonatomistic inputs, a similar atomistic form is assumed:

In[4]:=
SameQ @@ (ResourceFunction[
   "ProperLeafCount"] /@ {a[b][1, c[d, e][2, f[3]]], a[1, c[2, f[3]]]})
Out[4]=

Neat Examples (1) 

Compare ProperLeafCount with TreeCount:

In[5]:=
With[{randomTree = RandomTree[25]},
 SameQ @@ {ResourceFunction["ProperLeafCount"][
    TreeExpression[randomTree]],
   TreeCount[randomTree, _, {-1}]}]
Out[5]=

Publisher

Brad Klee

Version History

  • 1.0.0 – 07 March 2022

Related Resources

License Information