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.
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:
void
to n
newnode->left
or newnode->right
accordingly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.