Examples of Binary Tree sequence traversal based on C Language Data Structure
An example of Binary Tree sequence traversal using C language Data Structure
Time Limit: 1000 MS Memory Limit: 65536KB
Submit Statistic
Problem Description
It is known that a Character Sequence entered in the first order, such as abd, eg, cf, and (where, it indicates a null node ). Create a binary tree and obtain the hierarchical traversal sequence of the binary tree.
Input
The input data has multiple rows. The first row is an integer t (t <1000), indicating that there are t rows of test data. Each line is a string of less than 50 characters.
Output
The hierarchical traversal sequence of the output binary tree.
Example Input
2
Abd, eg, cf ,,,
Xnl, I, u ,,
Example Output
Abcdefg
Xnuli
#include
#include
#include
char s[60];
int i, j, k;
struct node
{
char data;
struct node *l, *r;
};
struct node *creat()
{
i++;
struct node *root;
if(s[i] == ',')
return NULL;
else
{
root = (struct node*) malloc (sizeof(struct node));
root -> data = s[i];
root -> l = creat();
root -> r = creat();
}
return root;
}
void cengci(struct node *root)
{
if(!root)
return;
struct node *q[100000], *p;
int f, r;
q[1] = root, f = r = 1;
while(f <= r)
{
p = q[f];
f++;
printf("%c", p -> data);
if(p -> l != NULL)
{
r++;
q[r] = p -> l;
}
if(p -> r != NULL)
{
r++;
q[r] = p -> r;
}
}
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
i = -1;
j = 0;
k = 0;
scanf("%s", s);
struct node *root;
root = creat();
cengci(root);
printf("\n");
}
return 0;
}