我正在尝试编写一个函数,它将使用级别顺序遍历将元素插入到二叉树中。我的代码遇到的问题是,当我在树中插入一个新节点后打印级别顺序遍历时,它会以无限循环的方式打印元素。号码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++ - 使用级别顺序遍历将节点插入二叉树,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36298462/

10-10 02:56