0

I am trying to implement a method to create a node to insert into a binary tree (not bst).

struct node{
       struct node *left;
       int data;
       struct node *right;
};

typedef struct node *n;

void createNewNode() {

     char r; // stands for response (whether or not a left or right child should be created)
     int d; //data to be stored in a node

     n newnode = new(struct node); //creates a new node

     cout<<"Enter data for the new node:"<<endl;
     cin>>d;
     newnode->data = d;

     cout<<"any left child? y/n"<<endl;
     cin>>r;
     switch (r) {
            case 's':
                 createNewNode(); // I thought to make it recursive and if a child is going to be created, then the method will call itself all over again
                 break;

            case 'n':
                 newnode->left = NULL; // if child is not created then pointer is NULL
                 break;
            }

     cout<<"any right child? y/n"<<endl;
     cin>>r;
     switch (r) {
            case 's':
                 createNewNode(); //recursive method again
                 break;

            case 'n':
                 newnode->right = NULL; // if child is not created then pointer is NULL
                 break;
            }
}

The problem that I am facing is when I use the recursive method to create a left or right child. I think it is not pointing to a value for the parent node created first. Am I right or wrong? I guess the question is whether or not I am linking the parent node to the right or left child node with the method I am trying to implement.

1 Answer 1

1

In createNewNode() function, you just create a new node and leave it without relating them to each other! You should bind it to left or right pointer.

This is what you should do:

  1. Change the output of this function from void to n
  2. At the end of function return the newly created node
  3. In both of the switch statements, where you call the function recursively, assign output of the function call to newnode->left or newnode->right accordingly.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.