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

2023-03-09 17:08:40 浏览数 (1)

代码语言:javascript复制
#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;
}

0 人点赞