Four Methods of binary tree traversal: pre-order traversal, middle-order traversal, post-order traversal, and hierarchical Traversal
Before reading the Traversal method, Let's first look at the Declaration of the binary tree class:
Class ctree
{
Public:
// To simplify the process, common data is used.
// Char is used for the data type. If you want to write a common class, you can use template <class T> to declare the template class.
Char treevalue;
Ctree * childleft, * childright;
Ctree ();
};
A binary tree is a recursive structure. Each node has a corresponding value and left and right subnodes. That is to say, access to a binary tree node takes only three steps: access to the root node, to access the left subtree of the Left subnode) and the right subtree of the right subnode ).
According to the order of access nodes, three different access methods are generated, that is, pre-order traversal, middle-order traversal, and post-order traversal.
The following is the implementation of the three methods, mainly using recursive functions)
Forward traversal:
Void preorderoutput (ctree * tree)
{
If (NULL! = Tree)
{
Cout <tree-> treevalue <"";
Preorderoutput (tree-> childleft );
Preorderoutput (tree-> childright );
}
}
In-order traversal:
Void inorderoutput (ctree * tree)
{
If (NULL! = Tree)
{
Inorderoutput (tree-> childleft );
Cout <tree-> treevalue <"";
Inorderoutput (tree-> childright );
}
}
Post-order traversal:
Void postorderoutput (ctree * tree)
{
If (NULL! = Tree)
{
Postorderoutput (tree-> childleft );
Postorderoutput (tree-> childright );
Cout <tree-> treevalue <"";
}
}
The preceding three recursive call methods are used to traverse a binary tree.
Hierarchical traversal:
Void levelorderoutput (ctree * tree)
{
// Save the nodes that can be accessed but not accessed to the queue. In fact, the sub-nodes of the current node are saved.
Queue <ctree *> treequeue;
Ctree * ptree;
Treequeue. push (tree );
While (! Treequeue. empty ())
{
// Access the current node
Ptree = treequeue. front ();
// Delete the accessed Node
Treequeue. pop ();
Cout <ptree-> treevalue <"";
// If the left subnode exists, insert the left subnode into the queue.
If (NULL! = Ptree-> childleft)
{
Treequeue. push (ptree-> childleft );
}
// If the right child node exists, insert the right child node into the queue
If (NULL! = Ptree-> childright)
{
Treequeue. push (ptree-> childright );
}
}
}
This article is from the "adwen2010" blog, please be sure to keep this source http://adwen2010.blog.51cto.com/1820717/1290649