Reputation: 19
So, I was trying to write a Binary tree code with only inserting, and it was working but after I delete some useless int
it stops working for some reason. Can anyone tell me why
So, here is my code, and it's working properly. But when I delete the int i=3;
in int main
it stops working. Why is that? Btw int i=3;
is just a random number it still works if I change it to some other number
#include<stdio.h>
#include<stdlib.h>
struct Treenode{
int data;
struct node*left;
struct node*right;
};
typedef struct Treenode Treenode;
struct Treenode* CreateTree(struct Treenode** tree, int num) {
Treenode*temp = NULL;
if(!(*tree))
{
temp = (Treenode*)malloc(sizeof(Treenode));
temp->left = temp->right = NULL;
temp->data = num;
*tree = temp;
return;
}
if(num < (*tree)->data){
CreateTree(&(*tree)->left, num);
}
else if(num > (*tree)->data){
CreateTree(&(*tree)->right, num);
}
}
void inorder(struct Treenode* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d \n", root->data);
inorder(root->right);
}
}
int main(){
int i = 3;
//creating tree
Treenode*root;
CreateTree(&root, 1);
CreateTree(&root, 2);
CreateTree(&root, 3);
CreateTree(&root, 4);
CreateTree(&root, 5);
CreateTree(&root, 6);
inorder(root);
return 0;
}
Upvotes: 0
Views: 40
Reputation: 75062
The non-static local variable Treenode *root;
is not initialized, so its initial value is indeterminate. Using such indeterminate value may cause some trouble.
Initialize the variable like Treenode *root = NULL;
to fix the issue.
Also note that casting results of malloc()
family is considered as a bad practice.
Upvotes: 3