编码二叉搜索树

时间:2014-03-19 19:48:58

标签: c loops binary-search-tree

根据我的编码类,左边的孩子是2 * i,右边的孩子是2 * i + 1

考虑到这一点,我编写了以下内容:

void max_heap( int key ){
    int leftkey = ( 2 * key ) + 1;
    int rigtkey = ( 2 * key ) + 2;
    printf( "key is: %d left child index is: %d right child index is: %d \n",
        key, leftkey, rigtkey );
    printf( "value at key is: %d left child is: %d right child is: %d \n",
        heap[key], heap[leftkey], heap[rigtkey] );

    if ( key >= 0 ){ // My base case?
        if ( leftkey < size && leftkey != size ){
            //Makes sure I don't go out of bounds

            if ( heap[leftkey] > heap[key] ){
                swap( &heap[leftkey], &heap[key] );

            }
        }
        else if ( rigtkey < size && rigtkey != size ){
            // Makes sure I don't go out of bounds

            if ( heap[rigtkey] > heap[key] ){
                swap( &heap[rigtkey], &heap[key] );

            }
        }
        max_heap( key-- );

    }
}

我用max_heap(size/2)调用方法,其大小是数组中的条目数。

当我运行程序并输入:

1 2 3 4 5 6

结果是:

key is: 3 left child index is: 7 right child index is: 8 
value at key is: 4 left child is: 0 right child is: 0 

key is: 3 left child index is: 7 right child index is: 8 
value at key is: 4 left child is: 0 right child is: 0 

key is: 3 left child index is: 7 right child index is: 8 
value at key is: 4 left child is: 0 right child is: 0 

key is: 3 left child index is: 7 right child index is: 8 
value at key is: 4 left child is: 0 right child is: 0 

...

它会像这样永远循环,并且不会进行任何交换。

1 个答案:

答案 0 :(得分:4)

问题在于你如何递归。您正在使用max_heap(key--);进行递归,这实际上意味着首先调用max_heap(key);,然后设置key = key - 1;&#34;。这为您提供了无限循环,因为每次调用您的函数都使用最初提供的相同键。如果预先递减(max_heap(--key);),您将获得更好的结果。

话虽这么说,这不是一个用递归解决的好问题。一个while循环会好得多。