【问题标题】:Inserting a node into a Binary Tree using Level Order Traversal使用级别顺序遍历将节点插入二叉树
【发布时间】:2016-07-17 20:16:04
【问题描述】:

我正在尝试编写一个函数,该函数将使用级别顺序遍历将元素插入二叉树。我的代码遇到的问题是,当我在将新节点插入树后打印级别顺序遍历时,它会在无限循环中打印元素。数字 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;
}

【问题讨论】:

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


    【解决方案1】:

    在这条线上

        temp -> left = &new_node;
    

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

    【讨论】:

    • 所以我应该发送要添加的节点而不是在本地创建节点?
    • @MutatingAlgorithm:那是合理的。
    • 只是好奇我如何通过发送实际元素(数字)而不是在 main 中创建节点来使其工作。
    • @MutatingAlgorithm:您需要以在函数返回后持续存在的方式分配它。
    • @MutatingAlgorithm:因为你的其余节点是在 main() 中的堆栈上分配的,所以在 main() 中创建新节点也是一致的,但或者,你可以有一些东西像std::list 的节点。您的插入函数可以传递对节点列表的引用。然后它将新节点添加到列表中并获取指向它的指针。
    猜你喜欢
    • 1970-01-01
    • 2017-08-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多