将节点插入二进制搜索树

时间:2012-06-15 16:49:56

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

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

    }

2 个答案:

答案 0 :(得分:1)

小心你的引用,那里。

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

答案 1 :(得分:0)

您正在分配新节点并将其填入,但从不更改现有节点中的指针以指向新节点。