将元素插入二叉搜索树时出错
Error while inserting element into binary search tree
该程序根据已排序的数字数组创建二叉搜索树,并向其中添加元素。
struct Tree
{
Tree *left_son, *right_son;
int head, key;
};
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
int mid = middle(left,right);
tree1->head = a[mid];
if (left != mid)
{
tree1->left_son = tree(a, left, mid-1);
}
if (right != mid)
{
tree1->right_son = tree(a, mid+1, right);
}
return tree1;
}
void add (Tree * curr_pos, int key)
{
if (key < curr_pos->head)
{
if (curr_pos->left_son != nullptr)
add (curr_pos->left_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->left_son = tmp_tree;
}
}
else
{
if (curr_pos->right_son != nullptr)
add (curr_pos->right_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->right_son = tmp_tree;
}
}
}
问题在行
if (curr_pos->left_son != nullptr)
,当节点没有剩余 "son" 时,由于某种原因条件满足,但不应该满足。我的意思是即使没有人,程序也会找到 left "son",并且指针会移动到那里。对不起,我的英语不好,但我希望有人能理解我说的话。
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
tree1->right_son = nullptr
tree1->left_son = nullptr
或者您可以通过向结构添加构造函数在结构树中执行相同的操作。
该程序根据已排序的数字数组创建二叉搜索树,并向其中添加元素。
struct Tree
{
Tree *left_son, *right_son;
int head, key;
};
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
int mid = middle(left,right);
tree1->head = a[mid];
if (left != mid)
{
tree1->left_son = tree(a, left, mid-1);
}
if (right != mid)
{
tree1->right_son = tree(a, mid+1, right);
}
return tree1;
}
void add (Tree * curr_pos, int key)
{
if (key < curr_pos->head)
{
if (curr_pos->left_son != nullptr)
add (curr_pos->left_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->left_son = tmp_tree;
}
}
else
{
if (curr_pos->right_son != nullptr)
add (curr_pos->right_son, key);
else
{
Tree * tmp_tree = new Tree;
curr_pos->right_son = tmp_tree;
}
}
}
问题在行
if (curr_pos->left_son != nullptr)
,当节点没有剩余 "son" 时,由于某种原因条件满足,但不应该满足。我的意思是即使没有人,程序也会找到 left "son",并且指针会移动到那里。对不起,我的英语不好,但我希望有人能理解我说的话。
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
tree1->right_son = nullptr
tree1->left_son = nullptr
或者您可以通过向结构添加构造函数在结构树中执行相同的操作。