Assume that the structure of a tree node is given: struct node {int data; struct node * left; struct node * right;} typedef strcut node * tree tells you to write code for Recursive tree traversal, in fact, it is very simple to traverse the following in the middle order: void traverse (tree T, (* visit) (INT) {If (! T) {traverse (t-> left, visit); (* visit) (t-> data); traverse (t-> right, visit );}} if you want to write non-recursive traversal, you have to worry about it. The most important thing to write this non-recursive traversal is to understand what happened in the recursion process, and try to simulate the entire process through iteration. # Include <stack> using namespace STD; void inorder_traverse (tree T, void (* visit) (INT) {tree P = T; stack <node *> S; while (p |! S. empty () {While (p) {S. push (p); P = p-> left;} p = S. pop (); (* visit) (p-> data); P = p-> right ;}}
Why do we have to write a non-recursive code?
I thought that non-recursion can avoid the time-space consumption caused by recursive calls, but I always felt that this reason was far-fetched.
Today I found a more convincing reason. The tree structure can be used to implement the container class, so we need to generate an iterator to traverse the entire container,
Therefore, we must use a non-recursive algorithm to return an element after each call to next and point the pointer to the next element.