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.
Result of php executing
Full code of max branch.php
- <?php
- $tree = [
- 1 => ['value' => 1, 'children' => [2,3]],
- 2 => ['value' => 2, 'children' => []],
- 3 => ['value' => 4, 'children' => [4,6]],
- 4 => ['value' => 8, 'children' => [5]],
- 5 => ['value' => 16, 'children' => []],
- 6 => ['value' => 32, 'children' => []],
- 7 => ['value' => 64, 'children' => [8]],
- 8 => ['value' => 100, 'children' => []],
- ];
- echo "Max #1: " . implode(", ", findMaxBranch($tree, 1)) . "\n";
- echo "Max #4: " . implode(", ", findMaxBranch($tree, 4)) . "\n";
- echo "Max #7: " . implode(", ", findMaxBranch($tree, 7)) . "\n";
- function findMaxBranch(array $arr, int $id) {
- $branch = [$id];
- if (empty($arr[$id]['children'])) {
- return $branch;
- }
- $max = [];
- foreach ($arr[$id]['children'] as $childId) {
- $current = findMaxBranch($arr, $childId);
- if (count($current) > count($max)) {
- $max = $current;
- }
- }
- if (empty($max)) {
- return $branch;
- }
- return array_merge($branch, $max);
- }