BST递归地定位节点

时间:2013-11-30 05:26:52

标签: c++ pointers recursion

我不是特别擅长使用递归,但我觉得在这种情况下需要使用它。在我的插入方法中,我使用递归检索方法来设置插入到所需位置的节点(在这种情况下,它应该定位到root-> right)。目前我使用插入方法两次,它填充root,但不填充root-> right。我在我的论证中使用了引用,所以我真的不确定为什么“找到”没有设置为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
}

0 个答案:

没有答案