Search code examples
phpdata-structuresbinary-treebinary-heap

Output heap as tree PHP


I have an array $heap = array(9, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9, 9, 8, 8, 9, 7, 9, 8, 8, 9, 9,); and I want to output It like binary tree, when the two children nodes we can know by this formulas, $heap[$key*2+1] and second $heap[$key*2+2]. I try to run using foreach but getting error about undefined offset 21. Here is foreach:

foreach ($heap as $key => $value) {
    echo $value;
    if ($key != count($heap)) {
        echo $heap[$key*2+1];
        echo $heap[$key*2+2];
    }
}

What I am doing wrong and how I can solve this?


Solution

  • I think the error in your check:

    if ($key != count($heap)) {
        echo $heap[$key*2+1];
        echo $heap[$key*2+2];
    }
    

    Here may be a situation with $key*2+2 is out of bounds the array. Add the check for it too. Try to use bool array_key_exists ( mixed $key , array $array ), something like this:

    if ($key != count($heap)) {
        if (array_key_exists($key*2 + 1, $heap)) echo $heap[$key*2 + 1];
        if (array_key_exists($key*2 + 2, $heap) ) echo $heap[$key*2 + 2];
    }
    

    As you point out in comment, you are doubling the values in your code. This can be avoided by recursive function, something like this (pseudocode):

    printArray(i, aHeap) {
        if (i < count($heap)) {
            echo $heap[i];
            printArray(2*i + 1, aHeap);
            printArray(2*i + 2, aHeap);
        }
    }