C 为每个二叉树插入函数
例如,如果我有2个二叉树:C 为每个二叉树插入函数,c,function,binary-tree,C,Function,Binary Tree,例如,如果我有2个二叉树: typedef struct node { int key; struct node *left, *right; } node; node* root1 node* root2 我已尝试使用此函数插入节点: void insert(node* root, int key) { node *p, *q; p = (node*) calloc(1,sizeof(node); p->key = key; if (r
typedef struct node {
int key;
struct node *left, *right;
} node;
node* root1
node* root2
我已尝试使用此函数插入节点:
void insert(node* root, int key) {
node *p, *q;
p = (node*) calloc(1,sizeof(node);
p->key = key;
if (root == NULL) {
root = p;
return;
}
q = root;
for (;;) {
if (key < q->key) {
if (q->left == 0) {
q->left = p;
return;
} else q = q->left;
} else if (key > q->key) {
if (q->right == 0) {
q->right = p;
return;
} else q = q->right;
} else {
free(p);
return;
}
}
}
void插入(节点*根,int键){
节点*p,*q;
p=(node*)calloc(1,sizeof(node);
p->key=key;
if(root==NULL){
根=p;
返回;
}
q=根;
对于(;;){
如果(键键){
如果(q->left==0){
q->左=p;
返回;
}否则q=q->左;
}否则如果(键>q->键){
如果(q->right==0){
q->右=p;
返回;
}else q=q->right;
}否则{
自由基(p);
返回;
}
}
}
但是在调用insert(root1,10)
之后,树root1
保持不变。我想这是因为函数中的root
变量在本地发生了更改
如何实现将作为参数接收要插入节点的树的函数?您可以始终返回指向根的指针,如下所示
node* insert(node* root, int key) {
node *p, *q;
p = (node*) calloc(1,sizeof(node));
p->key = key;
if (root == NULL) {
root = p;
return root;
}
q = root;
for (;;) {
if (key < q->key) {
if (q->left == 0) {
q->left = p;
return root;
} else q = q->left;
} else if (key > q->key) {
if (q->right == 0) {
q->right = p;
return root;
} else q = q->right;
} else {
free(p);
return root;
}
}
}
好的,要使指针本身的更改反映在外部,您需要将其作为双指针传入(
**
)。使用调用的asgcc-Wall-Wextra-g
编译您的C代码,然后使用和调试器了解程序的行为。请阅读编译器和调试器的文档。请注意,StackOverflow不是一个“做我的家庭作业”网站。还可以阅读关于s的内容,并研究源代码的灵感
node* root1 = NULL;
root1 = insert(root1,3)