1. 程式人生 > >SDUT3341資料結構實驗之二叉樹二:遍歷二叉樹

SDUT3341資料結構實驗之二叉樹二:遍歷二叉樹

cbegdfacgefdba
 #include <stdio.h>
 #include <stdlib.h>
 struct node
 {
     char data;
     struct node *lc,*rc;
 };
 char s[51];
 int c;
 struct node *CreatTree()
{
	struct node *root;
	char x;
	x=s[c++];

	if(x==',')
		return NULL;
	else
	{
		root=(struct node *)malloc(sizeof(struct node));
		root->data=x;
        root->lc=CreatTree();
        root->rc=CreatTree();
	}
return root;
}
void inPrintf(struct node *root)
 {
     if(root!=NULL)
     {
        inPrintf(root->lc);
        printf("%c",root->data);
        inPrintf(root->rc);
     }
 }
 void lastPrintf(struct node *root)
 {
     if(root!=NULL)
     {
        lastPrintf(root->lc);
        lastPrintf(root->rc);
        printf("%c",root->data);
     }
 }
 int main()
 {
     while(~scanf("%s",s))
     {
         c=0;
         struct node *root;
         root=(struct node *)malloc(sizeof(struct node));
         root=CreatTree();
         inPrintf(root);
         printf("\n");
         lastPrintf(root);
         printf("\n");
     }
 }