Consider the following class:
class TreeNode
{
int value;
public TreeNode l, r;
public TreeNode(int value)
{
this.value = value;
}
public IEnumerable<int> sub_values()
{
if (l != null)
foreach (int i in l.sub_values())
yield return i;
if (r != null)
foreach (int i in r.sub_values())
yield return i;
yield return value;
}
}
Each value is passed O(h)
times, where h
is the height of the tree. First, in yield return value;
statement, then in yield return i;
of each parent node.
So, sub_values
returns n
values using O(nh)
time complexity.
I can replace it with a method, which accepts a reference to a list of integers and instead of returning values, adds them to this list, but it won't be lazy anymore.
Can I return n
values in O(n)
and maintain laziness?