How to perform a breadth-first traversal of an expression?
breadthFirst[expr_] := Flatten[Table[Level[expr, {j}], {j, 0, Depth[expr]}], 1]
Running example:
expr = {{1, {2, 3}}, {4, 5}};
breadthFirst[expr]
(* Out[14]= {{{1, {2, 3}}, {4, 5}}, {1, {2, 3}}, {4, 5}, 1, {2,
3}, 4, 5, 2, 3} *)
Here is an expressly iterative solution:
bf[f_, x_] := ((f~Scan~#; #~Level~{2})& ~FixedPoint~ {x};)
(*
In[2]:= bf[Print, {{1, {2, 3}}, {4, 5}}]
{{1,{2,3}},{4,5}}
{1,{2,3}}
{4,5}
1
{2,3}
4
5
2
3
*)
Incorporating Rojo's advice to Hold
expressions gathered by Level
:
bf[f_, x_] := ( Level[f~Scan~#; #, {2}, Hold] & ~FixedPoint~ {x} ;)
Here is a simple implementation of a breadth first traversal. It simply maps the function onto each element on the current level and then collects all non-atomic entries into the next level, rinse and repeat.
breadthFirstApply[{}, call_] := Null
breadthFirstApply[list_, call_] := (call /@ list;breadthFirstApply[Level[list,{2}], call])
Output with your data structure:
breadthFirstApply[{{1, {2, 3}}, {4, 5}}, Print]
{1,{2,3}}(*level 1*) {4,5} (*level 1*) 1 (*level 2*) {2,3} (*level 2*) 4 (*level 2*) 5 (*level 2*) 2 (*level 3*) 3 (*level 3*)
Edit: Updated code based on feedback from Rojo