這裏是想,樹,插入節點在特定點
這不是一個二叉樹, 其實我可以在左側插入一個節點或右樹, 這給予的這一點。
所以,我想是在節點的左邊有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;
}
UPDATE:
對不起這裏的插入代碼
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);
}
}
你是什麼意思,「不起作用」。它沒有正確插入嗎?它會崩潰嗎?是否有編譯器錯誤? – Xymostech 2013-04-27 02:05:32
沒有錯誤,沒有崩潰,沒有插入節點, – Crashman 2013-04-27 02:15:58
'insert'定義在哪裏? – Beta 2013-04-27 02:30:40