I am trying to write a function that will insert an element into a Binary Tree using level order traversal. The issue i'm encountering with my code is that when I go to print the level order traversal after inserting a new node into the tree, it prints the elements in an infinite loop. The numbers 1 2 3 4 5 6 7 8 keep racing across the terminal. I would appreciate any pointers and advice on how to remedy this situation.
typedef struct BinaryTreeNode {
int data;
BinaryTreeNode * left;
BinaryTreeNode * right;
} BinaryTreeNode;
This is the level order traversal to print the elements:
void LevelOrder(BinaryTreeNode *root) {
BinaryTreeNode *temp;
std::queue<BinaryTreeNode*> Q {};
if(!root) return;
Q.push(root);
while(!Q.empty()) {
temp = Q.front();
Q.pop();
//process current node
printf("%d ", temp -> data);
if(temp -> left) Q.push(temp -> left);
if(temp -> right) Q.push(temp -> right);
}
}
This is where I insert an element into the tree by modifying level order traversal technique
void insertElementInBinaryTree(BinaryTreeNode *root, int element) {
BinaryTreeNode new_node = {element, NULL, NULL};
BinaryTreeNode *temp;
std::queue<BinaryTreeNode*> Q {};
if(!root) {
root = &new_node;
return;
}
Q.push(root);
while(!Q.empty()) {
temp = Q.front();
Q.pop();
//process current node
if(temp -> left) Q.push(temp -> left);
else {
temp -> left = &new_node;
Q.pop();
return;
}
if(temp -> right) Q.push(temp -> right);
else {
temp -> right = &new_node;
Q.pop();
return;
}
}
}
MAIN
int main() {
BinaryTreeNode one = {1, NULL, NULL}; // root of the binary tree
BinaryTreeNode two = {2, NULL, NULL};
BinaryTreeNode three = {3, NULL, NULL};
BinaryTreeNode four = {4, NULL, NULL};
BinaryTreeNode five = {5, NULL, NULL};
BinaryTreeNode six = {6, NULL, NULL};
BinaryTreeNode seven = {7, NULL, NULL};
one.left = &two;
one.right = &three;
two.left = &four;
two.right = &five;
three.left = &six;
three.right = &seven;
insertElementInBinaryTree(&one, 8);
LevelOrder(&one);
printf("\n");
return 0;
}
On this line
temp -> left = &new_node;
You are making temp->left
point to a local variable, which will no longer exist after the function returns. Any attempt to access it is undefined behavior.
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.