简体   繁体   English

使用C中的堆栈进行预遍历

[英]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. 我无法弄清楚为什么该程序只打印树的前3个字符。 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. 我将从工作堆栈实现开始,最好是使用自己的函数来推送和弹出内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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