The preamble of a binary tree inorder, preorder traversal non-recursive algorithm and level traversal algorithm

Original link: http://www.cnblogs.com/arcfat/archive/2012/11/21/2780432.html

Various non-recursive traversal of the binary tree, the more trouble to the ordinal numbers, because even if the left subtree is empty, the stack can not immediately, but to judge the right subtree. The following will be given the code:

typedef struct Tnode
{
ElemType data;
struct Tnode *lchild,*rchild;
}BBTnode,*BBTree;

struct typedef
{
BBTree Base *, * Top; // stack pointer member
int initsize; // stack initial length
} Stack;

// The following assumptions have been built and stack the binary tree

status NonFirstView (BBTree T, Stack S ) // nonrecursive preorder traversal
{
the while (S.base! S.top = T ||! = NULL)
{
the while (T! = NULL) // left come to the left
{
COUT T-<<> Data << ""; // output element
* S.top ++ = T;
T = T-> lchild;
}
T * = - S.top; // stack
T = T-> rchild; // the right steering
}
return the OK;
}

status NonMiddleView (BBTree T, Stack S ) // nonrecursive preorder
{
the while (S.base! S.top = T ||! = NULL)
{
the while (T! = NULL) // left come to the left
{
* S.top ++ = T;
T = T-> lchild;
}
T * = - S.top; // stack
cout << T-> data << "" ; // output element
T = T-> rchild; // the right steering
}
return the OK;
}

NonLastView Status (BBTree T, Stack S)
{
BBTree pre = NULL;
the while (!! S.base S.top = T || = NULL)
{
the while (! T = NULL) // go left leftmost
{
* ++ = T S.top;
T = T-> lchild;
}
T = * (S.top -. 1); // get node stack
if (T-> rchild == NULL || T-> rchild == pre) // If T is not the right child or right child which has just been visited
{
COUT T-<<> Data << ""; // output element
S.top--;
pre = T;
T = NULL;
}
the else
T = T-> rchild; // the right steering
}
return the OK;
}

status LevelView (BBTree T, Queue Q ) // traverse the level
{
IF (! T = NULL)
{
* Q.rear ++ = T;
the while (! = Q.front Q.rear) // queue is not empty
{
IF (T ! -> lchild = NULL) * Q.rear ++ = T-> lchild; // left subtree into the team
if (T-> rchild = NULL) * Q.rear ++ = T-> rchild; // right subtree into! Force
T = * Q.front ++; // dequeue
COUT T-<<> Data << "";
T * = Q.front; // latest HOL
}
}
return the OK;
}

 

Reproduced in: https: //www.cnblogs.com/arcfat/archive/2012/11/21/2780432.html

Guess you like

Origin blog.csdn.net/weixin_30565327/article/details/94789598