我打算使用排序数组构造一个平衡二叉搜索树。所有的工作都很好,直到节目结束。似乎二叉搜索树的析构函数有一些问题。C++析构函数,EXC_BAD_ACCESS,无法访问内存
错误信息:
计划接收信号EXC_BAD_ACCESS,无法访问内存。 原因:地址上的KERN_PROTECTION_FAILURE:0x00007fff5f3ffff8 0x0000000100002857 in BST_Node ::〜BST_Node(this = 0x100100920)at BST_Node.h:18〜BST_Node(){delete parent;删除左侧;删除 权;}
#ifndef BST_NODE_H
#define BST_NODE_H
#include <cstddef>
class BST_Node {
public:
BST_Node(int k) : key(k), parent(NULL), left(NULL), right(NULL) {}
~BST_Node() {if (parent!=NULL) delete parent;if (left!=NULL) delete left;if (right!=NULL) delete right;}
// data member
int key;
BST_Node* parent;
BST_Node* left;
BST_Node* right;
};
#endif
#include <iostream>
#include <vector>
#include "BST_Tree.h"
#include "BST_Node.h"
using namespace std;
// use recursion to construct the tree. Find the mid of the array to be the root of the subtree. Use left part of the array to construct the left subtree and right part to construct the right subtree.
BST_Node* CreateTree(vector<int> &a, int start, int end) {
if (end<start) {
return NULL;
} else {
int mid = (start+end+1)/2;
BST_Node* p = new BST_Node(a[mid]);
BST_Node* l_tmp = CreateTree(a, start, mid-1);
if (l_tmp)
l_tmp->parent = p;
p->left = l_tmp;
BST_Node* r_tmp = CreateTree(a, mid+1, end);
if (r_tmp)
r_tmp->parent = p;
p->right = r_tmp;
return p;
}
}
int main() {
vector<int> a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(6);
BST_Tree t;
t.root = CreateTree(a, 0, 6);
t.InOrderWalk(t.root);
return 0;
}
非常感谢您!
你有没有考虑过使用智能指针?这正是他们想要解决的问题 –
删除'删除父'。这不是如何进行递归调用, – Dan
所以你删除父母,它会运行父母的析构函数,它会删除它的左边和右边的孩子,谁会删除他们的父母。这将是一个问题。 – nos