0
#include<stdio.h>

struct tree
{
    int data;
    struct tree *left;
    struct tree *right;
};

struct tree *node1[100];
struct tree *node2[100];

int top1;
int top2;

void add(struct tree **root,int item)
{
    struct tree *ptr,*temp,*save;
    ptr=*root;

    if(ptr==NULL)
    {
        temp=(struct tree *)malloc(sizeof(struct tree));
        temp->data=item;
        temp->left=NULL;
        temp->right=NULL;
        *root=temp;
    }
    else
    {
        save=ptr;
        if((ptr->data)>item)
            ptr=ptr->left;
        else
            ptr=ptr->right;

        while(ptr!=NULL)
        {
            save=ptr;
            if((ptr->data)>item)
                ptr=ptr->left;
            else
                ptr=ptr->right;
        }

        if((save->data)>item)
        {
            temp=(struct tree *)malloc(sizeof(struct tree));
            temp->data=item;
            temp->left=NULL;
            temp->right=NULL;
            save->left=temp;
        }
        else
        {
            temp=(struct tree *)malloc(sizeof(struct tree));
            temp->data=item;
            temp->left=NULL;
            temp->right=NULL;
            save->right=temp;
        }
    }
}

void pushright(struct tree *ptr)
{
    top2=top2+1;
    node2[top2]=ptr;
}

void pushleft(struct tree *ptr)
{
    top1=top1+1;
    node1[top1]=ptr;
}

struct tree * popleft()
{
    struct tree *temp;
    temp=node1[top1];
    top1=top1-1;
    return temp;
};

struct tree * popright()
{
    struct tree *temp;
    temp=node2[top2];
    top2=top2-1;
    return temp;
};

void traversal()
{
    struct tree *ptr,*temp;
    ptr=popleft();
    while(ptr!=NULL)
    {
        printf("%d",ptr->data);
        ptr=popleft();
    }

    if(ptr==NULL)
    {
        temp=popright();
        if(temp!=NULL)
            pushing(temp);
    }
}

void pushing(struct tree *ptr)
{
    while(ptr!=NULL)
    {
        pushleft(ptr);
        if(ptr->right!=NULL)
        {
            top1=top1+1;
            node1[top1]=NULL;
            pushright(ptr->right);
        }
        ptr=ptr->left;
    }
    traversal();
}

void postoder(struct tree **root)
{
    struct tree *ptr;
    ptr=*root;
    if(ptr==NULL)
        printf("Tree is empty\n");
    else
    {
        pushing(ptr);
    }
}

int main()
{
    int k,m;
    struct tree *root;
    root=NULL;

    x:
    printf("Enter which thing u wana do\n1.Insertion\n2.Post Order Traversal\n");

    scanf("%d",&k);

    switch(k)
    {
        case 1:
            printf("Enter the number u wanna add\n");
            scanf("%d",&m);
            add(&root,m);
            goto x;

        case 2:
            top1=0;
            node1[top1]=NULL;
            top2=0;
            node2[top2]=NULL;
            postorder(&root);
            goto x;
    }
}
4

1 回答 1

4

你的代码有错别字

void postoder(struct tree **root)

应该

void postorder(struct tree **root)
//        ^

请注意,您还缺少<stdlib.h>. 添加后,您应该从malloc.

于 2013-09-30T09:04:18.847 回答