| Author: | Wojciech Muła |
|---|---|
| Added on: | 17.02.2011 |
This is a solution of some exercise from Cormen handbook (AFAIR exercise limited domain to binary trees). If you study algorithms and data structures, please DO NOT READ this text.
Obvious traversal algorithms require O(logn) memory, i.e. an explicit or implicit stack or queue.
Iterative algorithm described here performs depth-first-search and requires O(1) memory. In technical terms reference (or pointer) to one tree node is needed. This node, called p, is a node processed in previous step of algorithm.
Following properties of tree node x are needed:
For binary trees all of these functions are quite simple; main disadvantage is necessary to remember parent of each node.
Initial conditions:
In each iteration following cases are considered:
The processing ends in 4th case, when x is root and we try to reach its parent (impossible, isn't it).
To get pre-order scheme, visiting of node have to be performed after going deeper, i.e. in cases 2, 3 and 4 (see sample code).
Sample python implementation.