c - Original node changes when inserting nodes into binary tree -
i'm trying make binary tree using recursive insert function root node seems keep changing(if didn't, printf should give same output in code below). thoughts on how fix this?
typedef struct tnode{ char name[30]; int value; struct tnode *left; struct tnode *right; } tnode; tnode *insert(tnode *node, char *name, int value){ if(node==null){ tnode *temp = malloc(sizeof(struct tnode)); sprintf(temp->name,"%s",name); temp->value = value; temp->left = null; temp->right = null; return temp; } else if(strcmp(name,node->name)<0) { node->left = insert(node->left, name, value); } else if(strcmp(name,node->name)>0) { node->right = insert(node->right, name, value); } else{ printf("something went wrong\n"); } } int main(){ tnode *root = null; root = insert(root,"george",11); root = insert(root,"dick",12); printf("%s\n",root->name); root = insert(root,"walter",13); root = insert(root,"harry",13); printf("%s\n",root->name); root = insert(root,"zink",40); printf("%s\n",root->name); }
ok, we've figured out together. insert()
declared
tnode *insert(...)
so allways needs return pointer tnode, there cases in if-clause lead execution branch doesn't return anything. guess it's undefined return value.
since insert() operates recursively passing call "if you're leaf, put value here , return yourself", need handle case "and if you're not, ... and return ...". imagine have large tree , insert value, root passes call down binary structure until correct position found. final call (where recursion ends) return *tnode leaf previous call can correctly set node->left = insert(...);
, there still "open" calls on stack (since it's recursion) needs closed, i.e. function terminates , every node writes node->left
or node->right
. if don't return anything, there might arbitrary values break data structure , lead undefined behavior.
so, solution add return node;
@ end recursive calls can finalized leaving "passing" nodes between root , new leaf unchanged.
Comments
Post a Comment