2011-11-30 67 views
1

基本上發生的事情在我的插入功能是觸發放置節點到我的BST根右邊的部分會導致程序崩潰,我有不知道爲什麼。插入功能如下。對於崩潰我在與我的二叉搜索樹插入功能麻煩

node* insert(node *root, node *element) 
{ 

    // Inserting into an empty tree. 
    if (root == NULL) 
     return element; 
    else { 

     // element should be inserted to the right. 
     if (element->bk->key < root->bk->key) { 

      printf("Inserting in left position.\n"); 
      // There is a right subtree to insert the node. 
      if (root->left != NULL) 
       root->left = insert(root->left, element); 

      // Place the node directly to the right of root. 
      else 
       root->left = element; 
     } 

     // element should be inserted to the left. 
     else { 

      // There is a left subtree to insert the node. 
      if (root->right != NULL) 
       root->right = insert(root->right, element); 

      // Place the node directly to the left of root. 
      else 
       root->right = element; 
     } 

     // Return the root pointer of the updated tree. 
     return root; 
    } 
} 
+0

請你可以修復你的代碼縮進。 –

+2

你試過在調試器中運行這個嗎?那會告訴你它墜毀的路線,以及爲什麼。 –

+0

向我們展示在調用此函數之前如何初始化'element'。 – NPE

回答

1

最好的人選將是

if (element->bk->key < root->bk->key) 

因此,無論element->bkroot->bkNULL,或指向無處。

1

問題中的信息太少,無法確定,所以我們必須猜測。我認爲最可能的罪魁禍首是element可能無法正確初始化。這可能意味着以下任何一項:

  1. element不指向node的有效實例(未初始化的指針,懸擺指針等)。
  2. element->bk爲NULL或不是有效的指針。
  3. element->left輸入函數時不爲NULL。
  4. element->right輸入函數時不爲NULL。

順便說一句,該功能是一個複雜得多比它需要的是:

node* insert(node *root, node *element) { 
    if (root == NULL) 
     return element; // Inserting into an empty tree. 
    else { 
     if (element->bk->key < root->bk->key) { 
      printf("Inserting in left position.\n"); 
      root->left = insert(root->left, element); 
     } else { 
      printf("Inserting in right position.\n"); 
      root->right = insert(root->right, element); 
     } 
     // Return the root pointer of the updated tree. 
     return root; 
    } 
} 

注意兩個if (root->X != NULL)語句和兩個else條款如何是不必要的。使用root==NULL調用函數將會做正確的事情,這要感謝頂部的if (root==NULL)檢查。

0

調試步驟,我想借此:

  1. 運行在一個調試器
  2. 做不到這一點,你可以使用使用它們之間fflush(標準輸出)就這樣,如果你沒有得到一個打印您之前打印的一切知道這是初始化不好的一塊。
  3. 我會修復你的評論,以便他們真實地反映你正在做的事情(左右是在你的評論中倒退),這樣當你感到疲倦/沮喪時,你不會迷惑自己。
  4. 就像aix所說的簡化,這可能會解決您的問題(儘管可能不會),或者至少使調試器中的步驟,思考和閱讀變得更簡單。

如前所述,如果您給我們打電話/初始化我們可以提供更多幫助。