简体   繁体   English

使用级别顺序遍历将节点插入二叉树

[英]Inserting a node into a Binary Tree using Level Order Traversal

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. 数字1 2 3 4 5 6 7 8继续在终点站比赛。 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. 您正在使temp->left指向局部变量,该局部变量在函数返回后将不再存在。 Any attempt to access it is undefined behavior. 尝试访问它是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM