用堆栈实现C语言中的后序遍历

用堆栈实现C语言中的后序遍历,c,stack,traversal,postorder,C,Stack,Traversal,Postorder,我试图使用堆栈进行后序遍历…但是我遇到了一个错误,将无效操作数类型转换为二进制,,,,,,,,,请告诉我如何克服这种情况。 下面是代码 #include <stdio.h> #include <malloc.h> struct node { struct node *left; char data; struct node *right; }; struct node *buildtree(int); void post_order(struc

我试图使用堆栈进行后序遍历…但是我遇到了一个错误,将无效操作数类型转换为二进制,,,,,,,,,请告诉我如何克服这种情况。 下面是代码

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

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

struct node *buildtree(int);
void post_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");
    post_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 = buildtree(2*n+2);
    }

    return temp;
}

void post_order(struct node *root)
{
    struct node* stack[40];
    struct node* ptr;
    int top = 1;
    stack[1] = NULL;
    ptr = root;
    while(ptr != NULL)
    {
        top = top + 1;
        stack[top] = ptr;

        if((ptr->right) != NULL)
        {
            top = top + 1;
            stack[top] = -1 * (ptr->right);//how can i assign negative values on the stack.
        }

        ptr = ptr->left;
    }

    ptr = stack[top];
    top = top - 1;

    while(ptr > 0)
    {
        printf("%c", ptr->data);
        ptr = stack[top];
        top = top - 1;
    }

    if(ptr < 0)
    {
        ptr = (-1) * (ptr);
        while(ptr != NULL)
        {
            top = top + 1;
            stack[top] = ptr;
            if(ptr->right != NULL)
            {
                top = top + 1;
                stack[top] = (-1) * (ptr->right);
            }

            ptr = ptr->left;
        }
    }
}

结构节点是一个用户定义的对象,您试图对其应用乘法运算符。声明一个整数数组或堆栈的整数,并将指针转换为整数并推送到堆栈。弹出时,将整数转换为结构节点*,如下所示

int x = reinterpret_cast<int>(<your struct node pointer>);
x= x* -1;
push(x);
突然出现

int y = pop();
y= y*-1;
struct node *n = reinterpret_cast<struct BTNode*>(y);

这样您就可以解决这个问题。

以后请努力正确、干净地格式化代码。它不仅易于阅读,而且使其他人更有可能回答。@sandyroddick-Pointer不允许乘法/除法。它只适用于加法/减法。但是,它是否返回到安全位置取决于您操作的序列长度。@mahesh:那么我将如何为堆栈内容指定负值。请帮助me@Mahesh指针的乘法和除法都很好,它们在大多数情况下毫无意义。这段代码的问题是堆栈指针被重载为指针和布尔值的元组,假设从未使用指针的最高位。