I have two functions, insertNode and makeTree, both of which are supposed to modify the original tree they are being sent, but only makeTree does. Any changes made to the tree I am using in makeTree remain after the function ends, but any changes made to the tree in insertNode do not remain. I cannot figure out what the difference is and why one works, but the other does not. Thanks!
I am in the process of trying to debug another program, so the program I have now is not supposed to "do" anything.
Here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct treenode
{
int info;
treenode * left;
treenode * right;
} treenode;
void makeTree(treenode *tree);
void makeTreeNode(treenode *tree, int info);
void printNodes(treenode *tree);
void insertNode(treenode *tree, int val);
main(){
//create two trees, tree is balanced; tree2 is unbalanced
treenode *tree;
tree = (treenode *) malloc(sizeof(*tree));
//tree = NULL;
printf("Heading to make tree\n");
makeTree(tree);
insertNode(tree, 7);
printf("\nPrinting Result: ");
printNodes(tree);
/*
//create two trees, tree is balanced; tree2 is unbalanced
treenode *tree2;
//tree2 = (treenode *) malloc(sizeof(*tree));
tree2 = NULL;
printf("Heading to make Tree2\n");
makeTree(tree2);
insertNode(tree2, 4);
printf("\nPrinting Result: ");
printNodes(tree2);
*/
getchar();
return(0);
}
void insertNode(treenode *tree, int val){
printf("at insertnode\n");
if(tree==NULL){
printf("tree is null\n");
tree = (treenode *) malloc(sizeof(*tree));
tree->info = val;
tree->left = NULL;
tree->right = NULL;
printNodes(tree);
printf("back from printing\n");
}else{
printf("tree is not null\n");
printf("%d\n", tree->info);
if(tree->info==val) return;
printf("going to test ><\n");
if(tree->info>val){
printf("treeinfo >\n");
insertNode(tree->left, val);
}else{
printf("treeinfo <\n");
insertNode(tree->right, val);
}
}
return;
}
void printNodes(treenode *tree){
if(tree==NULL) return;
printNodes(tree->left);
printf("%d ", tree->info);
printNodes(tree->right);
return;
}
void makeTree(treenode *tree){
makeTreeNode(tree, 3);
treenode *tree12;
tree12 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree12, 2);
treenode *tree13;
tree13 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree13, 1);
treenode *tree14;
tree14 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree14, 8);
treenode *tree15;
tree15 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree15, 5);
treenode *tree16;
tree16 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree16, 4);
/*
treenode *tree17;
tree17 = (treenode *) malloc(sizeof(*tree));
makeTreeNode(tree17, 8);
*/
//put nodes into tree
tree->left = tree12;
tree->right = tree14;
tree12->left = tree13;
tree14->left = tree15;
//tree14->right = tree17;
tree15->left = tree16;
return;
}
void makeTreeNode(treenode *tree, int info){
tree->info = info;
tree->left = NULL;
tree->right = NULL;
return;
}