将节点插入二叉搜索树

Inserting a node into a Binary Search Tree

本文关键字:搜索树 插入 节点      更新时间:2023-10-16

我正在尝试实现一个简单的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局部变量。您需要传入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);

您正在分配一个新节点并将其填充,但永远不会更改现有节点中的指针以指向新节点。