tree + graph + comments - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of tree + graph + comments.php

  1. <?php
  2.  
  3. $tree = [
  4.         1 => ['value' => 1, 'children' => [2, 3]],
  5.         2 => ['value' => 2, 'children' => []],
  6.         3 => ['value' => 4, 'children' => [4,6]],
  7.         4 => ['value' => 8, 'children' => [5]],
  8.         5 => ['value' => 16, 'children' => [2]],
  9.         6 => ['value' => 32, 'children' => [6]],
  10.         7 => ['value' => 64, 'children' => [8]],
  11.         8 => ['value' => 100, 'children' => [7]],
  12. ];
  13.  
  14. echo "Graph #1: ", sumGraph($tree, 1), "\n";
  15. echo "Graph #3: ", sumGraph($tree, 3), "\n";
  16. echo "Graph #7: ", sumGraph($tree, 7), "\n";
  17.  
  18. // Another way to do it is to modify the existing tree. Mark element "visited" somehow
  19. // and exit recursion if it is marked. For example, assign value to null. Might be better 
  20. // if we want to minimize memory usage. If it is ok to modify it in the first place.
  21. function sumGraph(array $arr, int $id, array &$visited = []) {
  22.     if (isset($visited[$id])) {
  23.         return 0;
  24.     }
  25.     
  26.         $sum = $arr[$id]['value'];
  27.         $visited[$id] = 1;
  28.        
  29.         foreach ($arr[$id]['children'] as $childId) {
  30.             $sum += sumGraph($arr, $childId, $visited);
  31.         }
  32.        
  33.         return $sum;
  34. }
  35.  
  36. function sumTree(array $arr, int $id) {
  37.         $sum = $arr[$id]['value'];
  38.         foreach ($arr[$id]['children'] as $childId) {
  39.         $sum += sumTree($arr, $childId);
  40.         }
  41.        
  42.         return $sum;
  43. }
  44.  
  45.  
File Description
  • tree + graph + comments
  • PHP Code
  • 03 Oct-2023
  • 1.2 Kb
You can Share it: