在C中连接2个高度平衡树时的分割错误

时间:2014-07-16 03:59:23

标签: c join tree height

我正在尝试加入2个高度平衡树。为此目的,我在C中编写join()函数。我已经按照指令完成了所有操作,但是对于某些事情,它显示了分段错误。我知道当指针有错误时会发生分段错误。我想用C编写代码。我无法弄清楚坏指针在哪里。我无法理解我哪里做错了。在代码中,join()函数中有第2部分和第2.1部分。如果我能做到这一点,其余部分几乎完全相同。请告诉我代码中的错误和错误在哪里。请不要给任何粗鲁的评论,我正在学习先进的数据结构。先谢谢你。

// I have 2 trees tree1 and tree2. this part is the part when I am joining. there are other parts in the code, but other parts are identical to this part of the code. If I could figure out what I did wrong here, I can figure out for the rest part 

    // join() function
    tree_node_t *join(tree_node_t *tree1, tree_node_t *tree2, key_t separating_key)
    { tree_node_t *common_root, *tmp2, *new_node, *tmp_node, *tmp1, *up;
    int finished;
        //------------------introduction----------------------------------------------
        // we have 2 height balanced tree tree1 and tree2. these 2 trees are arguments. 

        // all keys in tree1 smaller than all keys of tree2

tree1->key < tree2->key;
//-----------------------------------------------------------------------------
//-------------------part 1----------------------------------------------------
while(abs(tree1->height - tree2->height) <= 1){
    common_root = get_node();// adding a common root 
    common_root->left = tree1;// putting tree1 at left
    tree1->upper = common_root;
    common_root->right = tree2;// putting tree2 at right
    tree2->upper = common_root; 
    common_root->key = separating_key;
}
//--------------------------------------------------------------------------------
//--------------------part 2------------------------------------------------------
while(tree1->height <= tree2->height - 2){
    tmp2 = tree2;
    /*while(tmp2->left != NULL){
        tmp2 = tmp2->left;
    }*/
    while(tmp2->left != NULL && tmp2->height <= tree1->height){
        // -------------------------start of part 2.1----------------------------
        while(tmp2->left != NULL && tmp2->height == tree1->height && tmp2->upper->height == tree1->height + 2){
            up = tmp2->upper;
            new_node = get_node();
            new_node->height = tree1->height + 1;
            up->left = new_node;
            new_node->right = tmp2;
            new_node->left = tree1;
            new_node = tmp2->upper;
            up = new_node->upper;
            new_node->key = separating_key;
            up->height = tree1->height + 2;
        }

0 个答案:

没有答案