数据结构实验之二叉树二:遍历二叉树 SDUT 3341

版权声明:欢迎转载,注明出处QWQ https://blog.csdn.net/Mercury_Lc/article/details/83861560
#include <bits/stdc++.h>
using namespace std;
struct Tree
{
    char data;
    struct  Tree *right;
    struct Tree *left;
};
char str[55];
int num;
struct Tree *creat()   
{
    struct Tree * root;
    if(str[num ++] == ',')
    {
        root = NULL;
    }
    else
    {
        root = (struct Tree *)malloc(sizeof(struct Tree));
        root -> data = str[num - 1];
        root -> left = creat();
        root -> right = creat();
    }
    return root;
}
void inorder(struct Tree * root) 
{
    if(root)
    {
        inorder(root -> left);
        printf("%c", root -> data);
        inorder(root -> right);
    }
}
void postorder(struct Tree * root) 
{
    if(root)
    {
        postorder(root -> left);
        postorder(root -> right);
        printf("%c", root -> data);
    }
}
int main()
{
    while(~scanf("%s",str))
    {
        num = 0;
        struct Tree * root;
        root = creat();
        inorder(root);
        printf("\n");
        postorder(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mercury_Lc/article/details/83861560