In-order Tree traversal options:
- 1. Recursion: uses the function stack space to store traversal information.
- 2. Stack with visited flag: requires a flag on every node, so more tree memory.
- 3. To reduce flag memory: method 2 but replace the node with a temporary object on entry and restore on exit.
- 3b. Use object recycling in 3 to reduce allocation costs.
- 4. Dual stack: method 3 but additional stack for flags
- 5. Parent pointer with next, current, and prev pointers. No stack. Tested code from someone's weblog on iterative methods.
- 6. Parent pointer with state-based traversal: Method 5 but store the state explicitly (i.e. going down left, going up, or going down right).
- 6.b. Optimization of 6 by short-circuiting loops.
- Additional comparison to usage of the built in Python array class also performed. (details)
Storage costs
O(log n) additional memroy: Recursion (1) and modified stack (3, 3b, 4) require overhead on the order of the depth of the tree, so these methods are comparable.
O(n) additional memory: Visited flag (2) and parent pointer (5, 6, 6b) require additional memory on the order of the tree size, so those require relatively more memory than O(lg n) storage methods.
Computation cost
All methods are O(N) and visit each node 1 to 3 times (additional visits when coming back up from each child). Thus, the difference is in the constants and may depend on the programming language.
Table of the results and graph available on a So it seems recursion is the way to go. It is the simplest to code, executes quickly, and uses low additional storage (O(lg n) is the least for the methods compared.)