Non-recursive dynamic binary tree with PHP

Go To StackoverFlow.com

2

I try to create a binary tree as html-table which is not recursive build. The order of the fields should be like this:

C1  C2  C3

         7
     3
         8
 1
         9
     4
        10

        11
     5
        12
 2
        13
     6
        14

C1 stands for col 1, C2 for col2 etc. The following code creates a table in a recursive way, but this is not what I want!

<?php 
$cols = 4; 
$counter = 0;
$lines = pow(2,$cols); 

echo '<table border=1 style="border:1px solid black;"> ';

    for($i = 0; $i < $lines; $i++){
        echo '<tr>';
            for($j = 0; $j < $cols; $j++){
                $rowspan = $lines/pow(2,$j+1);
                    if(0 === $i%$rowspan) {
                        $counter++;
                        echo '<td rowspan='.$rowspan.'>'.$counter;
                    }
            }
    }

echo '</table>';
?> 

I hope someone could give me a hint how to solve this problem.

2012-04-03 23:20
by Mannitou
What is the practical application? I.e. what problem are you trying to solve? Or is this homework - ghoti 2012-04-03 23:21
There is no recursion in your example - Basti 2012-04-03 23:30
Sorry for my unclear description. If you create a html-table, the cols and rows are build in the way like my php-script and this is like a recursive function. But I need the fields in the order shown in my example - Mannitou 2012-04-03 23:37


0

Used this expression to calculate the row's values: ($i / $rowspan + pow(2,$j+1) - 1) wherein $i / $rowspan is the number of the row in the current level starting with 0 for the first row and pow(2,$j+1) - 1 is the level's first value, i.e. 7 for the third level.

$cols = 4;
$lines = pow(2,$cols);

echo '<table border=1 style="border:1px solid black;">';

    for($i = 0; $i < $lines; $i++){
        echo '<tr>';
            for($j = 0; $j < $cols; $j++){
                $rowspan = $lines/pow(2,$j+1);
                    if(0 === $i%$rowspan) {
                         echo "<td rowspan='$rowspan'>".
                             ($i/$rowspan + pow(2,$j+1)-1).
                         "</td>";
                    }
            }
    }

echo '</table>';

Outputs your desired result. Hope your teacher won't hate me now! ;-)

You can alternativly use ($i/$lines + 1 ) * pow(2,$j+1) - 1 for the row's value, if you don't want to depend on $rowspan.

2012-04-04 00:12
by Basti
Great! The solution works perfect for me - Mannitou 2012-04-04 06:49
Ads