# Include <cstdlib>
# Include <iostream>
Using namespace STD;
Struct bitree // <declares the structure of a binary tree
{
Int data;
Bitree * left;
Bitree * right;
};
// Insert node Value
Bitree * insertnode (bitree * proot, int node)
{
Bitree * pcurrnode; // <declares the current node pointer
Bitree * pparentnode; // <declares the parent vertex pointer
Bitree * pnewnode = new bitree; // <create a new node memory space
Pnewnode-> DATA = node; // <contents of the saved Node
Pnewnode-> right = NULL; // <sets the initial value of the right pointer.
Pnewnode-> left = NULL; // <sets the initial value of the Left pointer.
If (proot = NULL)
Return pnewnode;
Else {
Pcurrnode = proot;
While (pcurrnode! = NULL ){
Pparentnode = pcurrnode;
(Node <pcurrnode-> data )? Pcurrnode = pcurrnode-> left: pcurrnode = pcurrnode-> right; // <insert a blank node.
}
(Pparentnode-> DATA> node )? Pparentnode-> left = pnewnode: pparentnode-> right = pnewnode;
}
Return proot;
}
// Create a binary tree
Bitree * creatbitree (INT data [], int Len)
{
Bitree * proot = NULL; // <root node pointer
For (INT I = 0; I <Len; I ++) // <create a Tree Structure
Proot = insertnode (proot, data [I]);
Return proot;
}
// Print Binary Tree
Void printbitree (bitree * proot)
{
Bitree * ppointer = proot-> left;
If (ppointer! = NULL)
Printf ("Left subtree node of root:/N ");
While (ppointer! = NULL ){
Printf ("[% 2D]/n", ppointer-> data );
Ppointer = ppointer-> left; // <points to the left Node
}
Ppointer = proot-> right;
If (ppointer! = NULL)
Printf ("right subtree node of root:/N ");
While (ppointer! = NULL ){
Printf ("[% 2D]/n", ppointer-> data); // <print node content
Ppointer = ppointer-> right; // <point to the right Node
}
}
// Pre-order traversal
Void preoder (bitree * ppointer)
{
If (ppointer! = NULL ){
Cout <ppointer-> data <"";
Preoder (ppointer-> left );
Preoder (ppointer-> right); // <node -- left subtree -- right subtree
}
}
// Release resources
Void release (bitree * proot)
{
If (proot = NULL)
Return;
Release (proot-> left );
Release (proot-> right );
Delete proot;
Proot = NULL;
}
Void main ()
{
Bitree * proot = NULL;
Int Index = 0, value;
Int nodelist [100] = {0 };
Printf ("Please input the elements of binary tree (exit for 0):/N ");
Scanf ("% d", & value );
While (value! = 0 ){
Nodelist [index ++] = value;
Scanf ("% d", & value );
}
Proot = creatbitree (nodelist, index); // <create a binary tree
Printbitree (proot); // <print the content of a binary tree node
Cout <"/nthe preoder travesal result is:" <Endl;
Preoder (proot );
Cout <Endl;
Release (proot); // <release resources
}