树的前序遍历顺序建立法(树的指针孩子表示法)
/*数的定义*/
#define m 3 //树的最大孩子个数
typedef char datatype;
typedef struct node{
datatype data;
struct node* child[m];
}node,*tree;
tree root;
tree createtree()
{
int i;char ch;
if((ch = getchar())== '#') t = NULL;
else{
t = (tree)malloc(sizeof(node));
t->data = ch;
for(i = 0;i < m;i++)
t->child[i] = createtree();
}
return t;
}
树的前序,后序遍历(递归)
void preorder(tree root)
{
int i;
if(root)
{
printf("%c",root->data);
for(i = 0;i < m;i++)
preorder(root->child[i]);
}
}
void postorder(tree root)
{
int i;
if(root)
{
for(i = 0;i < m;i++)
postorder(root->child[i]);
printf("%c",root->data);
}
}
树的层次遍历
void levelorder(tree t)
{
int i,f = 0,r = 1;
tree queue[100],p;
queue[0] = t;
while(f < r)
{
p = queue[f]; f++;
printf("%c",p->data);
for(i = 0;i < m;i++)
if(p -> child[i]){
queue[r] = p -> child[i];
r++;}
}
}