C-language tree structure exercise-sorting binary tree in the central order traversal, binary tree
Exercise in C-language tree structure-sequential traversal of a binary tree
Time Limit: 1000 MS Memory Limit: 65536KB
Submit Statistic
Problem Description
In the tree structure, there is a special binary tree called a sort binary tree. An Intuitive understanding is -- (1 ). each node contains a key value (2 ). the key value of the Left subtree of any node (if any) is smaller than that of the node (3 ). the key value of the right subtree of any node (if any) is greater than that of the node. Given a set of data, Please create an ordered binary tree for this set of data in the given order and output the result of sequential traversal.
Input
The input contains multiple groups of data. The format of each group is as follows.
The first line contains an integer n, which is the number of key values. The key value is expressed by an integer. (N <= 1000)
The second row contains n Integers to ensure that each integer is within the int range.
Output
Create a binary sorting tree for the given data and output the result of sequential traversal. Each output occupies one row.
Example Input
1
2
2
1 20
Example Output
2
1 20
#include
#include
#include
int i, s;
struct node
{
int data;
struct node * l, * r;
};
struct node * creat (struct node * root)
{
if (root == NULL)
{
root = (struct node *) malloc (sizeof (struct node)); // Apply for space. If you apply outside of if, it will not be NULL at the beginning and will enter else.
root-> data = s;
root-> l = NULL;
root-> r = NULL;
return root;
}
else
{
if (s> = root-> data)
{
root-> r = creat (root-> r);
}
if (s <root-> data)
{
root-> l = creat (root-> l);
}
}
return root;
}
int flag;
void zhongxv (struct node * root)
{
if (root)
{
zhongxv (root-> l);
if (flag)
printf ("% d", root-> data);
else
printf ("% d", root-> data);
flag ++;
zhongxv (root-> r);
}
}
int main ()
{
int t;
while (~ scanf ("% d", & t))
{
flag = 0;
struct node * root = NULL; // initialize first. And placed outside for the bad.
for (i = 0; i <t; i ++)
{
scanf ("% d", & s);
root = creat (root);
}
zhongxv (root);
printf ("\ n");
}
return 0;
}