c++ - 使用 Level Order Traversal 将节点插入二叉树

标签 c++ algorithm binary-tree tree-traversal

我正在尝试编写一个函数,使用层序遍历将一个元素插入到二叉树中。我在代码中遇到的问题是,当我在将新节点插入树后打印层级顺序遍历时,它会在无限循环中打印元素。数字 1 2 3 4 5 6 7 8 不停地跑过航站楼。对于如何解决这种情况的任何指示和建议,我将不胜感激。

typedef struct BinaryTreeNode {
    int data;
    BinaryTreeNode * left;
    BinaryTreeNode * right;
} BinaryTreeNode;

这是打印元素的层次顺序遍历:

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);
}
}

这是我通过修改层序遍历技术向树中插入一个元素的地方

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;
    }
}
}

主要

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;
}

最佳答案

在这条线上

    temp -> left = &new_node;

您正在使 temp->left 指向一个局部变量,该变量在函数返回后将不再存在。任何访问它的尝试都是未定义的行为。

关于c++ - 使用 Level Order Traversal 将节点插入二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298462/

相关文章:

algorithm - 运行合并排序和快速排序时的线性时间

python - 高效查找字符串是否包含一组字符(类似子串但忽略顺序)?

c++ - : expected constructor,析构函数错误,或者 '*' token之前的类型转换|

c++ - 指针错误

python - 二叉树节点位置和辅助字典

c++ - 在具有任意数量子节点的节点树中查找节点

C++,读取和保存大量数字

c++ - 如何将 unsigned int 转换为 unsigned char

.net - 如何计算 "kleinster gemeinsamer Nenner"最后公分母

c++ - .h 文件包含在头文件和 cpp 文件中