Aditya Nadig Aditya Nadig - 2 months ago 18
C Question

Reading a binary tree from the console in c

I am trying to read a binary tree into my program using the following function that i wrote.

void readTree(struct Dnode *root)
{
struct Dnode *temp;
struct Dnode *input;
char initData;

scanf(" %c",&initData);
input=CreateNode(initData);

if(initData==122){
printf("Leaf\n");
return;
}
else {
root=input;
temp=root;
printf("going to left of %c\n",initData);
readTree(root->lLink);
printf("going to right of %c\n",initData);
readTree(root->rLink);
}
}


Everything is working fine except the fact that , in main the tree doesnt exist. Here is my main program:

int main()
{
int n=0;
struct Dnode *root=NULL;
printf("Enter the tree as it asks. Enter z whenever there is no children :\n");
readTree(root);
printf("%c",root->data);
printf("In main");
return;

}


The program suddenly crashes after inputting the tree.Please help me.

Answer

You must understand that the values passed to a function as an argument and the parameter of the evoked function are the same, but totally different two local variables.

When your function readTree() is evoked, a local variable root is declared and the value is automatically initiated as the same value you passed into a function when evoked. The variable, root in main(), and the root in readTree() are different two variables but have the same value.

In the function readTree(), you're creating a new node and binding the returned value to the variable root in readTree(). As I wrote, the two roots are not identical. Therefore, your changes, bindings, have no effects out of the scope - readTree() and the root in main() remains unchanged.

To handle this problem, you must pass the pointer to pointer to struct Dnode.

Like this, in main function,

struct Dnode *root;
readTree(&root);

and readTree() must also be changed

readTree(struct Dnode **root)