The forward traversal of the binary tree is the first root node, and then if there is a Zuozi, then the left subtree is first ordered, then the right subtree is followed by its subtree.
The recursive algorithm is as follows
Copy Code code as follows:
void preorder (Betree *t)
{if (t==null) return;visit (t);//access the node preorder (t->lchild);p reorder (t->rchild);}
The recursive algorithm, of course, implicitly uses the stack. We carefully analyze this process, first took out the root node for access, and then we put the root node back stack, after the stack must have nodes into the stack, how to do? Root node can only directly access to Rchild and lchild, if it is Zuozi root node into the stack, then it is inevitable to visit, so it is rchild advanced stack, Lchild backward stack. Can draw a deeper understanding of the drawing.
So now write the first sequence traversal of the binary tree algorithm.
Copy Code code as follows:
void preorder (Betree *t)
{//algorithm we use one-dimensional arrays to simulate a sequential stack
if (t==null) return;//is empty tree there is absolutely no need to do the following
Betree * Stack[max];
top=1;stack[top]=t;//root node into stack
while (top>0)
{ nd=stack[top];//Remove the root node top=top-1;//back stack visit (nd->data);//Access root node if (nd- >rchild!=null {Top=top+1;stack[top]=nd->rchild}////root node has right subtree, put it into stack, wait until Zuozi is finished accessing
if (nd->lchild!=null) { Top=top+1;stack[top]=nd->lchild;}
}
}