max branch - 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 max branch.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' => []],
  9.         6 => ['value' => 32, 'children' => []],
  10.         7 => ['value' => 64, 'children' => [8]],
  11.         8 => ['value' => 100, 'children' => []],
  12. ];
  13.  
  14.  
  15. echo "Max #1: " . implode(", ", findMaxBranch($tree, 1)) . "\n";
  16. echo "Max #4: " . implode(", ", findMaxBranch($tree, 4)) . "\n";
  17. echo "Max #7: " . implode(", ", findMaxBranch($tree, 7)) . "\n";
  18.  
  19. function findMaxBranch(array $arr, int $id) {
  20.     $branch = [$id];
  21.  
  22.     if (empty($arr[$id]['children'])) {
  23.         return $branch;
  24.     }
  25.     
  26.     $max = [];
  27.     foreach ($arr[$id]['children'] as $childId) {
  28.         $current = findMaxBranch($arr, $childId);
  29.         if (count($current) > count($max)) {
  30.             $max = $current;
  31.         }
  32.     }
  33.     
  34.     if (empty($max)) {
  35.         return $branch;
  36.     }
  37.     
  38.     return array_merge($branch, $max);
  39. }
  40.  
  41.  
  42.  
File Description
  • max branch
  • PHP Code
  • 03 Oct-2023
  • 1005 Bytes
You can Share it: