Search code examples
phpdata-structurestreepreorder

What kind of data structure can be used in php for preorder traversal of tree?


enter image description here

Here I am attaching an image, which shows the tree, i want to travel in pre-order like

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

Which kind of data structure i can use in php for this structure ?


Solution

  • data structure

    simple associative array will do the job

    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);
    

    result

    1
    2
    5
    6
    3
    7
    8
    4
    9
    10
    11