简体   繁体   中英

pre_order traversal using stack in c

I am not able to figure out why the program is printing only first 3 characters of the tree. Please help.

#include <stdio.h>
#include <malloc.h>

struct node
{
    struct node *left;
    char data;
    struct node *right;
};

struct node *buildtree(int);
void pre_order(struct node*);

char  a[]={'a','b','c','d','e','f','g','\0','\0','h','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};

int main()
{
    struct node *root;
    root = buildtree(0);
    printf("pre order traversal:\n");
    pre_order(root);
}

struct node *buildtree(int n)
{
    struct node *temp = NULL;
    if(a[n]!='\0')
    {
        temp=(struct node*)malloc(sizeof(struct node));
        temp->left=buildtree(2*n+1);
        temp->data=a[n];
        temp->right=(2*n+2);
    }

    return temp;
}

void pre_order(struct node* root)
{
    char stack[30];
    struct node* ptr;
    int top=1;
    stack[1]=NULL;
    ptr=root;

    while(ptr!=NULL)
    {
        printf("%c",ptr->data);
        if(ptr->right!=NULL)
        {
            top=top+1;
            stack[top]=ptr->right;
        }

        if(ptr->left!=NULL)
            ptr=ptr->left;
        else
        {
            ptr=stack[top];
            top=top-1;
        }
    }
}

I'm surprised that compiled

char stack[30];

should be replaced by

struct node* stack[30];

There might be other problems.

You wrote a nice recursive routine to build the tree, why not write a recursive routine to do a pre-order traversal. It would be much easier to understand.

Simply calling something "stack" won't make it behave as one. When you push something onto a stack, the existing values get pushed down, and the reverse is true for popping.

I'd start with a working stack implementation, preferably with own functions for pushing and popping stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM