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.
Result of php executing
Full code of tree+graph.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' => [5]],
- 6 => ['value' => 32, 'children' => []],
- 7 => ['value' => 64, 'children' => [8]],
- 8 => ['value' => 100, 'children' => [7]],
- ];
- echo "Graph #1: ", sumGraph($tree, 1), "\n";
- echo "Graph #3: ", sumGraph($tree, 3), "\n";
- echo "Graph #7: ", sumGraph($tree, 7), "\n";
- function sumGraph(array $arr, int $id, array $visited = []) {
- if (isset($visited[$id])) {
- return 0;
- }
- $sum = $arr[$id]['value'];
- $visited[$id] = 1;
- foreach ($arr[$id]['children'] as $childId) {
- $sum += sumGraph($arr, $childId, $visited);
- }
- return $sum;
- }
- function sumTree(array $arr, int $id) {
- $sum = $arr[$id]['value'];
- foreach ($arr[$id]['children'] as $childId) {
- $sum += sumTree($arr, $childId);
- }
- return $sum;
- }