What is the algorithm for doing a post order traversal of a binary tree WITHOUT using recursion?
相关问题
- binary search tree path list
- How can I specify which relationship type to use a
- Yield all root-to-leaf branches of a Binary Tree
- How to find sum of node's value for given dept
- PHP script to automatically create file structure
相关文章
- Is there an existing solution for these particular
- Traversing an object getting the key and all paren
- How to traverse keys of a Hashtable in alphabetica
- Reconstructing binary tree from inorder and preord
- draw binary tree with php
- How to generate URL to view when using Traversal?
- making binary search tree
- Trying to implement path record for Haskell binary
Here is a solution in C++ that does not require any storage for book keeping in the tree.
Instead it uses two stacks. One to help us traverse and another to store the nodes so we can do a post traversal of them.
I was looking for a code snippet that performs well and is simple to customise. Threaded trees are not “simple”. Double stack solution requires O(n) memory. LeetCode solution and solution by tcb have extra checks and pushes...
Here is one classic algorithm translated into C that worked for me:
IMHO this algorithm is easier to follow than well performing and readable wikipedia.org / Tree_traversal pseudocode. For glorious details see answers to binary tree exercises in Knuth’s Volume 1.
Here's a sample from wikipedia:
Here I am pasting different versions in c# (.net) for reference: (for in-order iterative traversal you may refer to: Help me understand Inorder Traversal without using recursion)
~
Here is post order traversal with one stack (my version)
Using two stacks
With visited flag in C# (.net):
The definitions:
Unit Tests
Python with 1 stack and no flag:
And what is better is with similar statements, in order traversal works too
Please see this full Java implementation. Just copy the code and paste in your compiler. It will work fine.