1

スタックを使用してポスト オーダー トラバーサルを実行しようとしていましたが、バイナリへの無効なオペランド タイプのエラーが発生しました。この状況を克服する方法を教えてください。以下はコードです。

#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;
        }
    }
}
4

1 に答える 1

0

Struct ノードはユーザー定義オブジェクトであり、乗算演算子を適用しようとしています。スタックの整数配列または整数を宣言し、ポインタを整数に変換してスタックにプッシュします。ポップしながら、以下のように整数を struct node* に変換します。

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);

このようにして、この問題に取り組むことができます。

于 2013-06-20T08:04:17.633 に答える