c++ - 在 C++ 中将节点附加到树(引用和指针帮助。)

标签 c++

我正在为类编写平衡二叉树,但我对如何在 C++ 中使用指针和引用(直接来自 Java)感到困惑。下面的代码导致段错误,因为实际上没有节点被添加到树中,curr 刚刚被切换到新的 Node。我将如何着手使新的 Node 到达 curr 在树上指向的位置,而不是仅仅重新分配 curr

void BalancedTree::insert(int input)
{
    cout << "Insert started\n"; //DEBUG
    Node* trailingNode;
    Node* curr;

    curr = this->root;

    while(curr != NULL){
        cout << "Addloop\n";    //Debug
        if(input < curr->data){     //input smaller than current
            cout << "Left\n"; //DEBUG
            trailingNode = curr;
            curr = curr->left;
        }else{                      //input larger than current node
            cout << "Right\n"; //DEBUG
            trailingNode = curr;
            curr = curr->right;
        }
    }   

    insert(curr, input);
    cout << "test" << endl; 
    cout << root->data << " added\n";   //DEBUG
//  curr->parent = trailingNode;    //Set the parent

    size++;                         //Increase size
}

//Helper method
void BalancedTree::insert(Node*& curr, int input)
{
    curr = new Node(input);
}

最佳答案

如果我们有以下树并尝试插入值 3:

             2
            / \
       1 <--   --> 4
      / \         / \
     N   N       N   N

(N is NULL) 在 while 循环完成后:

  • trailingNode 指向值为 4
  • Node
  • currNULL(Node 的左分支,值为4)

然后 insert() 将一个新的 Node 分配给 curr 但永远不会将其附加到 Node 的左分支code> 的值为 4

要附加,您可以更改对 insert() 的调用:

insert(input < trailingNode->data ?
           trailingNode->left :
           trailingNode->right,
       input);

您需要处理树为空的情况。还有其他方法可以实现这一目标,但希望这会为您指明正确的方向。

关于c++ - 在 C++ 中将节点附加到树(引用和指针帮助。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9324791/

相关文章:

c++ - 在 C++ 中正确实现复制构造函数

c++ - : Handle, 指针和引用有什么区别

c++ - 类内定义友元函数的范围?

c++ - 如何在 C++ 中加速平面到打包/交错图形?

c++ - 使用 int vector 元素作为输入的递归方法类

c++ - QGL小部件: Using setFormat() To Enable Multisampling = The Window Doesn't Close

c++ - 打开文件进行 I/O 并使用命令行重定向

c++ - gdb:将内存地址转换为 STL 对象

c++ - 错误 LNK2001 : unresolved external symbol __imp__PathRemoveFileSpecA@4

c++ - DEV C++ 行 69 [错误] 'i' 的名称查找已更改为 ISO 'for' 范围 [-fpermissive]