tree+graph - 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.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' => [5]],
  9.         6 => ['value' => 32, 'children' => []],
  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. function sumGraph(array $arr, int $id, array &$visited = []) {
  19.     if (isset($visited[$id])) {
  20.         return 0;
  21.     }
  22.     
  23.         $sum = $arr[$id]['value'];
  24.         $visited[$id] = 1;
  25.        
  26.         foreach ($arr[$id]['children'] as $childId) {
  27.             $sum += sumGraph($arr, $childId, $visited);
  28.         }
  29.        
  30.         return $sum;
  31. }
  32.  
  33. function sumTree(array $arr, int $id) {
  34.         $sum = $arr[$id]['value'];
  35.         foreach ($arr[$id]['children'] as $childId) {
  36.         $sum += sumTree($arr, $childId);
  37.         }
  38.        
  39.         return $sum;
  40. }
  41.  
  42.  
File Description
  • tree+graph
  • PHP Code
  • 03 Oct-2023
  • 963 Bytes
You can Share it: