程序从排序的数字数组中创建二叉搜索树,并向其添加元素。
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)
,当节点没有离开&#34; son&#34;时,条件由于某种原因而满足,但它不应该。我的意思是程序找到了左边的儿子&#34;即使没有人,指针也会移动到那里。对不起,我的英语不好,但我希望有人能理解我说的话。
答案 0 :(得分:1)
Tree *tree(int *a, int left, int right)
{
Tree *tree1 = new Tree;
tree1->right_son = nullptr
tree1->left_son = nullptr
或者您可以通过向结构添加一个构造函数在结构树中执行相同的操作。