2011-11-30 65 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所说的简化,这可能会解决您的问题(尽管可能不会),或者至少使调试器中的步骤,思考和阅读变得更简单。

如前所述,如果您给我们打电话/初始化我们可以提供更多帮助。