2016-05-14 50 views
0

我很困惑,我在做什麼錯誤。爲什麼不按預訂,後序和中序打印樹。我在我困惑的代碼行旁寫下了我的問題。另外我不明白如何與結構相關。C中的二叉搜索樹。

#include <stdio.h> 
#include<stdlib.h> 

typedef struct BST_{ 
    int data; 
    struct BST_ *lchild, *rchild, *parent; 
}BST; 

typedef struct BiTree_{ 
    int size; 
    BST *root; // is it possible to relate this root with the pointer parent of type BST? i yes then how? 
}BiTree;; 
BST *temp; 
BST *createNode(int data){ 
    BST *new_ele; 
    new_ele=(BST*)malloc(sizeof(BST)); 
    new_ele->data=data; 
    new_ele->lchild=NULL; 
    new_ele->rchild=NULL; 
    new_ele->parent=NULL; 
    return new_ele; 
    } 

void insertNode(BST *temp,BST *r,int data){ 
    if(temp==NULL){ 
      temp=createNode(data); 
     } 

    else if(temp->data >= r->data){ 
      if(r->rchild==NULL){ 
       r->rchild=temp; 
      } 
      else{ 
       insertNode(r->rchild,temp,data); 
      } 
    } 
    else if(temp->data <= r->data){ 
      if(r->lchild==NULL){ 
       r->lchild=temp; 
      } 
      else{ 
       insertNode(r->lchild,temp,data);  
          } 
    } 
// return r->data; //why cann't i do this? 
} 

void preorder(BST *r){ 
    if(r!=NULL){ 
     printf("%d",r->data); 
     preorder(r->lchild); 
     preorder(r->rchild); 
    } 
} 
void inorder(BST *c){ 
    if(c!=NULL){ 

     inorder(c->lchild); 
     printf("%d",c->data); 
     inorder(c->rchild); 
    } 
} 
void postorder(BST *r){ 
    if(r!=NULL){ 
     postorder(r->lchild); 
     postorder(r->rchild); 
     printf("%d",r->data); 
    } 
} 
void delet(BST *r){ 
    if(r!=NULL){ 
     free(r); 
    } 
} 
void main(){ 
    BST *new_node,*r=NULL; 
    BiTree *search; 
    search=malloc(sizeof(BiTree)); 
    search->root=NULL; 
    search->size=0; 
    int i,a,n,data; 
    printf("Enter the number of element to be inserted\n"); 
    scanf("%d",&n); 
    printf("Enter the data\n"); 
    for(i=0;i<n;i++){ 
      scanf("%d",&data); 


      insertNode(temp,r,data); 
      // printf("Enter the data %d\n",r->data); // unable to print this 

      search->size++; 
      } 
    printf("size is %d\n",search->size); 

    preorder(r);// why cann't i print the data of r. r is the root of the tree. 
    postorder(r); 
    inorder(r); 
    delet(r); 

} 
+0

請通過提供輸入,預期輸出和實際輸出來更準確地描述程序的行爲。 – kaylum

+2

'r'永遠不是NULL。 – hobbs

+0

它只是要求輸入並給出大小。在那裏我想打印預先訂購的樹,後序和中序,然後刪除它。我不知道如何解決它。 –

回答

1
  • //是有可能涉及這根與類型BST的指針父? ?我是那麼如何*

請重新表述這個問題

  • //返回R->數據; //爲什麼我不能這樣做?

函數void insertNode(BST *temp,BST *r,int data){的簽名是說什麼都不應該返回。改變這個

  • printf(「輸入數據%d \ n」,r-> data); //無法打印此

在功能r被初始化爲NULL,並沒有在功能上改變了這種

  • 爲什麼水溼我打印R系列的數據。 r是樹的根。

見上面

1

temp點未設置爲NULL,我想如果它不是NULL,它將會有垃圾了。 用這個你的insertNode()函數不會分配內存,而且這個函數裏面的所有代碼完全依賴於temp的垃圾值。

+0

使它無效後,它仍然不起作用 –

+0

很晚迴應抱歉,它可能無法正常工作,因爲其他問題。但是這個初始化是必要的。你有沒有試圖把它放在調試器下?如果沒有,讓我知道 - 我會做的。 – pankaj