我计划使用排序数组来构建平衡的二叉搜索树。一切运行良好,直到程序结束。看来二叉搜索树的析构函数有问题。
错误信息:
程序收到信号 EXC_BAD_ACCESS,无法访问内存。原因:KERN_PROTECTION_FAILURE 地址:0x00007fff5f3ffff8 0x0000000100002857 在 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;
}
非常感谢!