0
該程序根據排序後的數字數組創建二叉搜索樹並向其中添加元素。將元素插入二叉查找樹時出錯
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)
,當節點沒有左「兒子」,條件滿足某種原因,但它不應該。我的意思是程序發現離開「兒子」,即使沒有人,指針移動到那裏。對不起,我的英語不好,但我希望有人能理解我說的話。
你是否總是將left_son和right_son初始化爲nullptr? – ivanw
@ivanw可能不是,我應該在哪裏做這個?謝謝你回答btw! –