Example of traversing a tree in depth:
class Node: def __init__(self, value): self._value = value self._children = [] def add_child(self, child): self._children.append(child) def __iter__(self): return iter(self._children) def depth_first(self): yield self for c in self: yield from c.depth_first()
I understand that yield from does not consume the generator immediately, but instead pass yield up to its caller.
But this transfer process still exists, and thus yield will be passed from every node to its root, and we can describe the execution time by repeating (suppose this is a binary tree for simplicity, but the idea is the same):
T (n) = 2 * T (n / 2) + Ξ (n)
Ξ(n) exists because this node must pass all the yield passed from its descendants to the parent. And the time complexity obtained by the formula above:
About (NlogN)
However, the time complexity of tree traversal is only O(n) , if I do not use yield or yield from .
I am wondering if I donβt understand how yield works, or is it just impossible to write a recursive generator like this.
source share