这是想法,
这不是二叉树,实际上我可以在树的左侧或右侧插入一个节点,这就是这个。
所以,我想要的是在节点左侧插入 5 作为值:节点下方的新节点以 5 作为值,新节点值 13
问题是当我尝试在节点处插入 10 作为值时,不起作用。更新:不插入节点,不崩溃,不错误
这是代码。
struct bin_tree {
int data;
struct bin_tree * right;
struct bin_tree * left;
};
typedef struct bin_tree node;
enum Ruta{
LEFT,
RIGHT
};
void insertSide(node ** tree, int val, Ruta r)
{
node *temp = NULL;
if(!(*tree))
{
temp = new node();
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}
if(r == LEFT)
{
if ( &(*tree)->left == NULL)
{insert(&(*tree)->left, val);}
else{insertSide(&((*tree)->left),val,r);}
}
else
{
if ( &(*tree)->right == NULL)
{insert(&(*tree)->right, val);}
else{insertSide(&((*tree)->right),val,r);}
}
}
node * searchDeep(node ** tree,int valSearch,bool & f)
{
node * temp;
if((*tree))
{
if(valSearch == (*tree)->data)
{
f = true;
temp = new node();
temp->left = temp->right = NULL;
temp->left = (*tree)->left;
temp->right = (*tree)->right;
temp->data = (*tree)->data;
*tree = temp;
return *tree;
}
if (f == false){
searchDeep(&((*tree)->left), valSearch,f);
searchDeep(&((*tree)->right), valSearch,f);
}
}
}
void insertAt(node ** tree, int valSearch,int valNew,Ruta r)
{
node * temp;
bool f;
f =false;
temp = searchDeep(tree,valSearch,f);
insertSide(&temp,valNew,r);
}
int main()
{
node *root;
node *tmp;
insertSide(&root,9,LEFT);
insertSide(&root,5,RIGHT);
insertSide(&root,10,LEFT);
insertSide(&root,25,LEFT);
insertSide(&root,45,LEFT);
insertSide(&root,3,RIGHT);
insertAt(&root,5,13,LEFT);
//this does not work
//insertAt(&root,10,9,RIGHT);
return 0;
}
更新:
对不起,这里是插入代码
void insert(node ** tree, int val)
{
node *temp = NULL;
if(!(*tree))
{
temp = new node();
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}