简体   繁体   English

迭代地将新节点添加到二叉树中,根被覆盖

[英]Iteratively adding a new node to a binary tree, root getting overwritten

I found the needed code to iteratively add new nodes, though it doesn't work in my case. 我发现需要的代码来迭代添加新节点,尽管在我的情况下它不起作用。

 // bal=left  jobb=right
void bkf::beszur(int k) {
    if(root != NULL) 
        while (true) {
            if (k < root->data) {
                if (root->bal == NULL) {
                    root->bal = new node;
                    root->bal->data = k;
                    root->bal->bal = NULL;
                    root->bal->jobb = NULL;
                    break;
                }
                else
                    root = root->bal;   // overwrites root
            }
            else 
                if (root->jobb == NULL) {
                    root->jobb = new node;
                    root->jobb->data = k;
                    root->jobb->bal = NULL;
                    root->jobb->jobb = NULL;
                    break;
                } else 
                    root = root->jobb;   // overwrites root
        }
    else {
        root = new node;
        root->data = k;
        root->bal = NULL;
        root->jobb = NULL;
    }
}

At "root = root->bal" the root gets overwritten, so so it takes the data and left and right node of root->bal too. 在“ root = root-> bal”处,根将被覆盖,因此它也需要数据以及root-> bal的左右节点。 I also tried creating a "node *p", and assigning root to it, but that way it allocates memory for p itself, not where p is pointing to. 我还尝试创建一个“节点* p”,并为其分配根,但是那样,它会为p本身而不是p所指向的位置分配内存。 Here's the declaration: 这是声明:

struct node {
    int data;
    node *bal;
    node *jobb;
};

class bkf {
    node *root;
    // ...

How is this done properly? 如何正确完成?

Maybe the point is that you don't store your root node before doing the traversing/inserting inside the tree. 也许关键是您在树中进行遍历/插入之前不存储根节点。 Hence root is an arbitrary node after calling the function. 因此,root是调用函数后的任意节点。

Maybe you should store the root before first function call to always have the entry point to start again. 也许您应该在第一个函数调用之前存储根,以始终使入口点再次启动。

Because root is the class level scope variable. 因为root是类级别范围变量。 Make a local copy of root, let's say root_local. 制作root的本地副本,比方说root_local。

root_local = root. root_local =根。

And then start using it in the function. 然后开始在函数中使用它。

when you do the root = root->bal. 当您执行root = root-> bal时。 root is changed at class level. 在类级别更改root。

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

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