2013-11-01 194 views
0

我改编了本书的代码:数据结构和算法由Mark Allen Weiss编写,第3版。二叉搜索树删除节点

每当我运行它,它崩溃。通过请求,我将添加整个二叉树代码(其长)。每当我试图在调试模式下运行它,我结束了在remove()功能前三如果else语句之间循环,然后我最终得到这样的输出:在项目4Draft

“未处理的异常在0x0007300d。 exe:0xC0000005:访问冲突读取位置0x003c0000。“

我很确定这是一个段错误,只是试图找到源代码。另外,当我运行它时,它不会步入findMin(),但我将它包含在内,因为它在删除内,并且尚未完全测试。任何人都可以帮我导出源代码吗?

下面是删除功能:

void remove(const T& x, TreeNode * & tn) const { 
    if(tn == NULL) 
     return; 
    else if(x < tn->data) 
     remove(x, tn->left); 
    else if(tn->data < x) 
     remove(x, tn->right); 
    else if(tn->left != NULL && tn->right != NULL) {//Two Children(Swap the min of the right subtree, and swap 
     tn->data = findMin(tn->right)->data; 
     remove(tn->data,tn->right); 
    } 
    else{ 
     TreeNode *oldNode = tn; 
     tn = (tn->left != NULL) ? tn->left : tn->right; 
     delete oldNode; 
    } 

} 

这里是findMin():

TreeNode * findMin(TreeNode *x) const { 
     if(debugMode==true){ 
     cout << "\nWERE IN FINDMIN\n"; 
     } 
     if(x==NULL){ 
      return NULL; 
     } 
     if(x->left==NULL){ 
      if(debugMode==true){ 
      cout << x; 
      } 
      return x; 
     } 

     return findMin(x->left); 
    }; 

这里是我在我的测试文件中称:

cout << "Checking remove()\n"; 
    for(int i =SIZE; i>0;i++){ 
     z.remove(x[i]); 
    } 
    cout << "DONE Checking remove()\n"; 

回答

5

你确定你的循环条件是正确的?

for(int i =SIZE; i>0;i++){ 
    z.remove(x[i]); 
} 
cout << "DONE Checking remove()\n"; 

也许你应该写类似:

for(int i = 0; i < SIZE; i++){ 
    z.remove(x[i]); 
} 

for(int i = SIZE - 1; i >= 0; i--){ 
    z.remove(x[i]); 
} 
+1

完全正确;该描述使它看起来像一个无限循环或堆栈粉碎,这表明它是。 –

+0

我现在看到它,我花了我所有的时间在看类的功能。多谢你们! – TaylorTheDeveloper