[英]post_order traversal in C using stack
我正在嘗試使用堆棧進行后處理遍歷.....但是我得到一個錯誤的類型,將無效的操作數轉換為二進制,請告訴我如何克服這種情況。 下面是代碼。
#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;
}
}
}
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);
這樣,您可以解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.