# Binary tree traversal non-recursive

### Non-recursive binary tree traversal using the stack to achieve

- Since the order was to begin with, you should access node encountered, the next step should be downstream along the left branch of the tree.
- However, nodes and branches have not visited, and therefore needs to be recorded, and the node onto the stack.
- The null tree is traced back, remove the stack and a branch, like a binary tree as traversing it.

#### Code:

1 def preorder(t, proc): 2 s = Stack() 3 while t is not None or s not s.is_empty(): 4 while t is not None: 5 proc(t.data) 6 if t.right: 7 s.push(t.right) 8 t = t.left 9 t = s.pop()

### Traverse through the generator function

When writing program in Python, considering the data collection structure, always should think of iterators. The following is a non-recursive implementation visiting Binary Tree iterator:

1 def preorder(t): 2 s = Stack() 3 while t is not None or not s.is_empty(): 4 while t is not None: 5 if t.right: 6 s.push(t.right) 7 yield t.data 8 t = t.left 9 t = s.pop()