简体   繁体   English

编码二叉搜索树

[英]coding a binary search tree

According to my coding class, the left child is 2 * i and the right child is 2 * i + 1 . 根据我的编码类,左孩子是2 * i ,右孩子是2 * i + 1

With this in mind, I coded the following: 考虑到这一点,我编写了以下代码:

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

    }
}

I call the method with max_heap(size/2) , with size being the number of entries in the array. 我用max_heap(size/2)调用该方法,其中size是数组中的条目数。

When I run the program and enter: 当我运行程序并输入:

1 2 3 4 5 6

The result is: 结果是:

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 

...

It loops forever like that and no swapping is ever done. 它像这样永远循环,永远不会进行交换。

The problem is with how you're recursing. 问题在于您如何递归。 You're recursing with max_heap(key--); 您将使用max_heap(key--); which effectively means "first call max_heap(key); and then set key = key - 1; ". 这实际上意味着“先调用max_heap(key);然后设置key = key - 1; ”。 This gives you an endless loop since each call to your function is made with the same key that was originally provided. 这给您一个无休止的循环,因为对函数的每次调用都是使用最初提供的相同键进行的。 You will get better results if you pre-decrement ( max_heap(--key); ). 如果先递减( max_heap(--key); ),将会得到更好的结果。

That being said, this is not a good problem to solve with recursion. 话虽如此,这不是递归解决的好问题。 A while loop would be much better. 一会儿循环会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM