简体   繁体   English

非递归动态二叉树 PHP

[英]Non-recursive dynamic binary tree with PHP

I try to create a binary tree as html-table which is not recursive build.我尝试创建一个二叉树作为 html 表,它不是递归构建。 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! C1 代表 col 1,C2 代表 col2 等。下面的代码以递归的方式创建一个表,但这不是我想要的!

<?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.我希望有人能给我提示如何解决这个问题。

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, ie 7 for the third level.使用此表达式计算行的值: ($i / $rowspan + pow(2,$j+1) - 1)其中$i / $rowspan是当前级别中的行数,第一个从0开始row and pow(2,$j+1) - 1是级别的第一个值,即第三级别的7

$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.如果您不想依赖 $rowspan,您可以交替使用($i/$lines + 1 ) * pow(2,$j+1) - 1作为行的值。

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

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