PHP二叉树实现
我需要在PHP中实现“完美二叉树” 目前,我有:PHP二叉树实现,php,data-structures,binary-tree,Php,Data Structures,Binary Tree,我需要在PHP中实现“完美二叉树” 目前,我有: <?php $teams = 8; $num_rounds = round(log($teams, 2)) + 1; for ($i = 0; $i < $num_rounds; ++$i) { $matches = $teams * pow(.5, $i - 1) / 2; for ($j = 0; $j < $matches; ++$j) { echo "<d
<?php
$teams = 8;
$num_rounds = round(log($teams, 2)) + 1;
for ($i = 0; $i < $num_rounds; ++$i)
{
$matches = $teams * pow(.5, $i - 1) / 2;
for ($j = 0; $j < $matches; ++$j)
{
echo "<div style=\"border-style: inset;\"><span>Round $i Match $j</span></div>\n";
}
}
?>
您可以查看它。我使用插件来显示数据,但正如我之前所说的,我相信我需要一个二叉树来正确显示数据
如果有更好的方法,或者我只是做错了?解决方案是什么?从中,您的树条目将显示如下:
0
\
1
/ \
2 \
\
3
/ \
4 / \
\ / \
5 \
/ \
6 \
\
7
/
8 /
\ /
9 /
/ \ /
10 \ /
\ /
11
/
12 /
\ /
13
/
14
num_rounds = x
num_games = (2 ^ num_rounds) - 1
game_names = array(num_games)
for round = 0 to num_rounds - 1
index = (2 ^ round) - 1
increment = 2 ^ (round + 1)
game_number = 0
while index < num_games
game_names[index] = sprintf("round %s, game %s", round, game_number)
game_number++
index += increment
display_tree(game_names)
其中,树中的每个数字表示其在输入数组中的项的索引。请注意,倒计时第一轮列,索引将上升2。在第二列中,它们上升了4,在第三列中上升了8
我将创建一个字符串数组,其中包含每个游戏的名称。然后像这样做:
0
\
1
/ \
2 \
\
3
/ \
4 / \
\ / \
5 \
/ \
6 \
\
7
/
8 /
\ /
9 /
/ \ /
10 \ /
\ /
11
/
12 /
\ /
13
/
14
num_rounds = x
num_games = (2 ^ num_rounds) - 1
game_names = array(num_games)
for round = 0 to num_rounds - 1
index = (2 ^ round) - 1
increment = 2 ^ (round + 1)
game_number = 0
while index < num_games
game_names[index] = sprintf("round %s, game %s", round, game_number)
game_number++
index += increment
display_tree(game_names)
num_rounds=x
num_游戏=(2^ num_回合)-1
游戏名称=数组(num\u游戏)
对于轮数=0到轮数-1
索引=(2^轮)-1
增量=2^(四舍五入+1)
游戏编号=0
而指数
这是在php中实现二叉树(数据结构)的代码:
括号在这里显示得很好。也许我应该重新措辞,这些标签是不正确的,即使我按顺序遍历它们。括号显示本身很好。预期的输出是每列是一个0 1 2 3的圆,匹配项在每列中按顺序显示。进一步的研究使我相信我需要一个BST,具有顺序遍历。如何在BST中正确获取数据是我无法理解的。我根据数组(4,2,6,1,3,5,7)构建了这个数组;这是因为匹配的数量降低到了7(4个参与者)。您需要学习如何使用编辑器中的格式化工具,以便代码能够正确显示。看见