C++ BST递归定位一个节点

C++ BST递归定位一个节点,c++,pointers,recursion,C++,Pointers,Recursion,我并不特别擅长使用递归,但我觉得在这种情况下需要使用它。在我的插入方法中,我使用递归检索方法将要插入的节点设置为所需的位置(在本例中,它应该定位到root->right)。目前我使用了两次insert方法,它填充root,但不填充root->right。我在参数中使用了passby引用,所以我真的不确定为什么“find”没有设置为root->right int Tree::insert_node(char artist[], char title[], char album[], int len

我并不特别擅长使用递归,但我觉得在这种情况下需要使用它。在我的插入方法中,我使用递归检索方法将要插入的节点设置为所需的位置(在本例中,它应该定位到root->right)。目前我使用了两次insert方法,它填充root,但不填充root->right。我在参数中使用了passby引用,所以我真的不确定为什么“find”没有设置为root->right

int Tree::insert_node(char artist[], char title[], char album[], int length) { // For adding a song node to the tree
    if(0 == root->a_song.is_empty()) { // If root is empty, fill it first
        root->a_song.set(artist, title, album, length); // Set the members of the node's song
    }
    else { // fill a leaf instead
        node* fill_node; // new node to be inserted
        retrieve(root, fill_node, artist, title); // set fill_node to it's proper position on the tree
        fill_node = new node;
        fill_node->left = NULL;
        fill_node->right = NULL;
        fill_node->a_song.set(artist, title, album, length);
    }
    //FOR TESTING, REMOVE LATER
    if(NULL == root->right)
        cout << endl << "RIGHT IS NULL" << endl; // This is being output after the first AND second insert
    else
        cout << endl << "RIGHT IS NOT NULL" << endl;
    return 0;
}

int Tree::retrieve(node* & last, node* & found, char artist[], char title[]) {
    //simple case: node*last is NULL, meaning found is set to the correct position
    if(NULL == last) {
        found = last;
        return 1;
    }
    else if(1 ==  last->a_song.compare(artist, title)) { // If artist or title is less, go left
        retrieve(last->left, found, artist, title);
    }
    else if(-1 == last->a_song.compare(artist, title)) { // If artist or title is greater, go right
        // I've tested, and the method is going to this case on the second insertion
        retrieve(last->right, found, artist, title);
    }
    else
        return 0; //zero indiciates the song you're trying to insert already exists
}
int-Tree::插入_节点(char-artist[],char-title[],char-album[],int-length){//用于将歌曲节点添加到树中
如果(0==root->a_song.is_empty()){//如果root为空,请先填充它
root->a_song.set(艺术家、标题、专辑、长度);//设置节点歌曲的成员
}
否则{//将填充一片叶子
node*fill_node;//要插入的新节点
检索(根、填充节点、艺术家、标题);//将填充节点设置为其在树上的正确位置
填充节点=新节点;
填充节点->左=空;
填充节点->右=空;
填充节点->歌曲集(艺术家、标题、专辑、长度);
}
//对于测试,请稍后删除
如果(空==根->右)

您的代码可能有很多问题。首先,检索的某些情况下不返回值。此外,当您将“查找”设置为正确位置时,您只将其设置为NULL。您应该返回对父节点的引用,而不是NULL。谢谢,我改为返回父节点,结果成功了。