A nonrecursive algorithm for binary tree preorder traversal

  • 2020-04-02 02:11:10
  • OfStack

The preorder traversal of a binary tree is the root node first, and then the left subtree if there is a left subtree, and then the right subtree if there is a right subtree.
The recursive algorithm is as follows

 void   preorder(Betree *t)
{   if(t==null) return;visit(t);//Access the node preorder(t-> Lchild); Preorder (t -> Rchild); }

Of course the recursive algorithm implicitly USES the stack. We carefully analyze this process, first took out the root node to access, and then we put the root node back to the stack, after the stack must have nodes back to the stack, what do we do? The root node can only access rchild and lchild directly. If the root node of the left subtree enters the stack, it must be accessed later, so it must be rchild advanced stack and lchild backward stack. You can draw pictures to deepen your understanding.
So now I'm going to write out the algorithm for traversing the binary tree in order.

void preorder(Betree *t)
{ //In the algorithm we use a one-dimensional array to simulate a sequential stack
     if(t==null) return;//There is no need to do the following for an empty tree & NBSP; & have spent & have spent & have spent
     Betree *stack[max];
     top=1;stack[top]=t;//The root node is pushed
     while(top>0)
    {   nd=stack[top];// Take out the root node   top=top-1;// Return a stack    visit(nd->data); // Accessing the root node  if(nd->rchild!=null) { top=top+1;stack[top]=nd->rchild;} // The root node has a right subtree, push it on the stack, and wait until the left subtree is accessed 
if(nd->lchild!=null) { top=top+1;stack[top]=nd->lchild;}
   }
}

Related articles: