简体   繁体   English

非递归二叉树insert()方法不起作用

[英]non recursive binary tree insert() method not working

I have written a binary tree code for inserting elements into it in non-recursive method. 我编写了一个二进制树代码,用于在非递归方法中将元素插入其中。 The code is not working as intended. 代码未按预期工作。 Regardless of how many times I debug the code, nothing seems to be wrong but I am getting wrong results. 无论我调试代码多少次,似乎都没有错,但我得到了错误的结果。 I am hoping you guys can help. 我希望你们能帮忙。 Thanks in advance. 提前致谢。

void insert(int element){
    if(root == NULL){
        struct elemq *node;
        node = (struct elemq *)malloc(sizeof(struct elemq));
        node->ele = element;
        node->left = NULL;
        node->right = NULL;
        root = node;
        cout << root->ele << "\n";
    }
    else{
        struct elemq *ref;
        ref = root;
        while(ref != NULL){
            if(element <= ref->ele){
                if(ref->left == NULL){
                    struct elemq *node;
                    node = (struct elemq *)malloc(sizeof(struct elemq ));
                    node->ele = element;
                    node->left = NULL;
                    node->right = NULL;
                    ref->left = node;
                    break;
                }
                else{
                    ref = ref->left;
                }
            }
            else if(element > ref->ele){
                if(ref->right == NULL){
                    struct elemq *node;
                    node = (struct elemq *)malloc(sizeof(struct elemq ));
                    node->ele = element;
                    node->left = NULL;
                    node->right = NULL;
                    ref->right = node;
                    break;
                }
                else{
                    ref = ref->right;
                }
            }
        }
    }
}

Every time I try to insert an element, each element is being treated as root , not only the first time. 每次我尝试插入一个元素时,每个元素都被视为root ,而不仅仅是第一次。 So, every time, the condition if(root == NULL) is true . 因此,每次条件if(root == NULL)true I declared root as global variable and initialized it to NULL in main() . 我将root声明为全局变量,并在main()中将其初始化为NULL I came to know this by putting cout << in the first if() condition. 我通过将cout <<放在第一个if()条件中来了解这一点。 I modified my previous post to this new question. 我将之前的帖子修改为这个新问题。

node = ref->left;

You want 你要

ref->left = node;

and similar for the ref->right 并且类似于ref-> right

I think you are mistakenly setting the node that you are adding to the references, instead of setting the left and right references to the node you are adding. 我认为您错误地设置了要添加到引用的节点,而不是设置对要添加的节点的左右引用。 Change node = ref->left to ref->left = node , and likewise for the right. node = ref->left改为ref->left = node ,同样改为right。

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

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