什么样的数据结构可以在php中用于树的前序遍历?

时间:2014-12-04 05:32:05

标签: php data-structures tree preorder

enter image description here

这里我附上了一张图片,显示了树,我想按照预订顺序旅行

1,2,5,6,3,7,8,4,9,10,11。

我可以在php中使用哪种数据结构来构建这种结构?

1 个答案:

答案 0 :(得分:1)

数据结构

简单关联数组将完成工作

array(2) {
  ["data"]=> int
  ["children"]=> array()
}

<强> PHP

<?php

function makeTree($data, $children = array()) {
  $tree = array();
  $tree['data'] = $data;
  $tree['children'] = $children;

  return $tree;
}

function traverse($tree) {
  echo $tree['data'] . "\n";

  foreach($tree['children'] as $child) {
    traverse($child);
  }
}

$root = makeTree(1, array(
   makeTree(2, array(makeTree(5), makeTree(6))),
   makeTree(3, array(makeTree(7), makeTree(8))),
   makeTree(4, array(makeTree(9), makeTree(10), makeTree(11)))
));

traverse($root);

<强>结果

1
2
5
6
3
7
8
4
9
10
11