c++ - 将节点插入二叉搜索树

标签 c++ visual-c++ c++11

我正在尝试实现一个简单的 C++ 函数,该函数在给定要插入的节点的值和 BST 的根的情况下将节点添加到二叉搜索树。
令人惊讶的是,我无法插入任何元素。尽管我确保编译器输入了我插入节点的语句,但树中没有我要添加的任何节点。我认为问题可能在于我如何在函数参数中传递节点。任何人都可以帮忙吗?谢谢。这是我的节点类型和函数的实现。

 struct Node{

    int value;
    Node *left;
    Node *right;
    };

    //this method adds a new node with value v to Binary Search Tree
    // node is initially the root of the tree
    void Push_To_BST(Node* node,int v)
    {

    // the right place to add the node
    if(node==NULL)
    {

    node=new Node();
    node->value= v;
    node->left= NULL;
    node->right=NULL;

    }

    //the value to be added is less than or equal the reached node
    else if(v <= node->value)
        {
    //adding the value to the left subtree
    Push_To_BST(node->left,v);
    }

    //the value to be added is greater than the reached node
    else if(v > node->value)
    {
    //adding the value to the right subtree
    Push_To_BST(node->right,v);
    }

    }

最佳答案

小心你的引用,那里。

void Push_To_BST(Node* node,int v) 
{ 

// the right place to add the node 
if(node==NULL) 
{  
    node=new Node(); 
    // etc

您要为其分配内存的节点 是一个本地 变量。您需要传入 Node** 才能将指向新创建节点的指针传出

例子:

void Push_To_BST(Node** pnode,int v) 
{ 
    Node* node = *pnode;

    // the right place to add the node 
    if(node==NULL) 
    {  
        node=new Node(); 
        // etc
    }
    else if(v < node->value)  
    {  
        //adding the value to the left subtree  
        Push_To_BST(&node->left,v);  
    }  
    // etc

并称它为

Node* n = new Node;
Push_To_BST(&n, 2);

关于c++ - 将节点插入二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11055014/

相关文章:

c++ - 队列实现正在失去对头节点的跟踪

由 C++ CRTP stack corruption

c++ - OpenCV逐帧视频拼接

c++ - 单个函数的两个可变参数模板?第2部分

c++ - 在不使用模板的情况下将多个大小的数组传递给虚拟方法

c++ - ECS——一个实体是否可以拥有多个给定类型的组件

c++ - 前向声明从嵌套模板中隐藏祖先模板参数

c++ - 图形生成器未发布,渲染在后台

C++ 模板 : conditionally enabled member function

C++11 在成员函数上应用 result_of,失败,为什么?