2011-08-03 35 views
1

我試圖做一個使用堆棧的後序遍歷.....但我得到一個錯誤類型無效操作數到二進制,,,,,,,,,請告訴我如何克服這種情況。下面是 是代碼。在C中使用堆棧post_order遍歷

#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; 
     } 
    } 
} 
+1

未來,請努力正確(並乾淨)地格式化您的代碼。它不僅更容易閱讀,而且更容易回覆。 –

+0

@sandyroddick - 指針不允許乘/除。它僅適用於加/減法。但是,它是否返回到安全位置取決於您操作的序列長度。 – Mahesh

+0

@mahesh:那麼我將如何分配負值堆棧的內容..請幫助我 – sandyroddick

回答

0

看看this的線程。他們討論二叉樹的無序遞歸遍歷。接受的答案給出了基於堆棧的解決方案的鏈接。

0

結構節點是一個用戶定義的對象,您試圖將乘法運算符應用於它。聲明一個整數數組或整數堆棧並將指針轉換爲整數並推入堆棧。彈出時將整數轉換爲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); 

這樣就可以制定出這個問題。