Binary tree is a very important data structure, many other data organizations are based on the binary Tree Foundation evolved. The binary tree has the front, the middle, and the last three ways to traverse, because the tree itself is defined by recursion, therefore, the recursive method to achieve three traversal, not only the code is simple and easy to understand, but its cost is relatively large, and if the use of a non-recursive method to achieve three traversal, the stack to simulate the implementation (recursion is also implemented by the stack). The following is a brief introduction to the recursive implementation of the three traversal modes, and the implementation of the three traversal methods in detail.
Recursive implementation of one or three traversal methods (simpler, not detailed here)
1, the first sequence traversal-according to the "root node-left child-right child" in the order of access.
void Pre_traverse (Btree pTree)
{
if (pTree)
{
printf ("%c", ptree->data);
if (ptree->plchild)
pre_traverse (ptree->plchild);
if (ptree->prchild)
pre_traverse (ptree->prchild);
}
}
2, in-sequence traversal--in accordance with the "left child-root node-right child" in the order of access.
void In_traverse (Btree pTree)
{
if (pTree)
{
if (ptree->plchild)
In_traverse (ptree- >plchild);
printf ("%c", ptree->data);
if (ptree->prchild)
in_traverse (ptree->prchild);
}
}
3, sequential traversal--in accordance with the "left child-right child-root node" in the order of access.
void Beh_traverse (Btree pTree)
{
if (pTree)
{
if (ptree->plchild)
Beh_traverse (ptree-> Plchild);
if (ptree->prchild)
beh_traverse (ptree->prchild);
printf ("%c", Ptree->data);
}
Non-recursive implementation of two or three kinds of traversal methods
For the sake of understanding, the two-fork tree of the following diagram is an example to analyze the implementation of three traversal methods of binary tree.