简体   繁体   English

将节点插入二叉搜索树

[英]Inserting a node into a Binary Search Tree

I am trying to implement a simple C++ function that adds a node to a Binary Search Tree given the value of the node to be inserted, and the root of the BST. 我正在尝试实现一个简单的C ++函数,该函数将给定要插入节点的值和BST的根的节点添加到二进制搜索树中。
Surprisingly, I am not able to push any element. 令人惊讶的是,我无法推动任何因素。 Although I made sure that the statement where I am inserting the node is entered by the compiler, the tree did not have any of the nodes I am trying to add. 尽管我确保编译器输入了要插入节点的语句,但是树没有要添加的任何节点。 I think the problem could be in how I am passing the node in the function argument. 我认为问题可能出在我如何在函数参数中传递节点。 Anyone can help? 有人可以帮忙吗? Thank you. 谢谢。 Here's my Node type and the implementation of the function. 这是我的Node类型和该函数的实现。

 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);
    }

    }

Careful with your referencing, there. 在那里仔细参考。

void Push_To_BST(Node* node,int v) 
{ 

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

The node you are allocating memory to is a local variable. 您要分配内存的node局部变量。 You would need to pass in a Node** in order to pass out a pointer to a freshly created node. 您需要在通过Node**为了一个指针传递一个新创建的节点。

Example: 例:

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

and call it like 并称它为

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

您正在分配一个新节点并进行填充,但从未更改现有节点中的指针以指向该新节点。

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

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