# Include <stdio. h>
# Include <malloc. h>
# Define elemtype char
// Create the data structure type of the tree
Typedef struct tree
{
Elemtype data;
Struct tree * lchild, * rchild;
} Tree, * stree;
// Tree Creation
Void create (stree & T) // note that references must be used here
{
Elemtype da;
Scanf ("% C", & Da );
If (da = '*')
T = NULL; // return NULL;
Else
{
// P = (stree) malloc (sizeof (tree ));
T = (stree) malloc (sizeof (tree ));
T-> DATA = da;
Create (t-> lchild );
Create (t-> rchild );
}
}
// First-order traversal of the tree
Void preorder (stree T)
{
If (t)
{
Printf ("% C", T-> data );
Preorder (t-> lchild );
Preorder (t-> rchild );
}
}
// Ordinal traversal of the tree
Void midorder (stree T)
{
If (t)
{
Midorder (t-> lchild );
Printf ("% C", T-> data );
Midorder (t-> rchild );
}
}
// Post-order traversal of the tree
Void postorder (stree T)
{
If (t)
{
Postorder (t-> lchild );
Postorder (t-> rchild );
Printf ("% C", T-> data );
}
}
// Obtain the leaf node of the tree
Void countleaf (stree T, Int & COUNT)
{
If (t)
{
If (t-> lchild = NULL & T-> rchild = NULL)
{
Printf ("leaf node: % C/N", T-> data );
Count ++;
}
Else
{
Countleaf (t-> lchild, count );
Countleaf (t-> rchild, count );
}
}
}
// Calculate the depth of the tree
Int depth (stree T)
{
Int D, LD, RD;
If (t = NULL)
D = 0;
Else
{
LD = depth (t-> lchild );
RD = depth (t-> rchild );
D = LD> RD? Ld: RD;
D ++;
}
Return D;
}
// Main function section
Void main ()
{
Int count, DEP;
Stree T = NULL;
Printf ("Enter the sequence of the tree:/N ");
// Test data: ABC ** de * g ** F ***
Create (t );
Printf ("result of first-order traversal:/N ");
Preorder (t );
Printf ("/N ");
Printf ("result of sequential traversal:/N ");
Midorder (t );
Printf ("/N ");
Printf ("result of post-order traversal:/N ");
Postorder (t );
Printf ("/N ");
Count = 0;
Countleaf (T, count );
Printf ("the number of leaf nodes in the tree is % d/N", count );
Dep = depth (t );
Printf ("the depth of the tree is % d/N", DEP );
}
/*
Enter the sequence of the tree:
ABC ** de * g ** F ***
Result of first-order traversal:
Abcdegf
Result of the Middle-order traversal:
Cbegdfa
Result of post-order traversal:
Cgefdba
Leaf node: c
Leaf node: G
Leaf node: F
The number of leaf nodes in the tree is: 3
The depth of the tree is: 5
Press any key to continue
*/