Back to home

Test FileTreesRunning Tests
PHP Trees main image

PHP Trees

This expects an installation on the system of phpunit.

Test File

Create tree_test.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 <?php require "tree.php"; class TreeTest extends PHPUnit\Framework\TestCase { public function testBFS() { $n4 = new Node(4); $n5 = new Node(5); $n2 = new Node(2, [$n4]); $n3 = new Node(3, [$n5]); $n1 = new Node(1, [$n2,$n3]); $t = new Tree($n1); $expected = [1,2,3,4,5]; $this->assertEquals($expected, $t->bfs()); } public function testDFS() { $n4 = new Node(4); $n5 = new Node(5); $n2 = new Node(2, [$n4]); $n3 = new Node(3, [$n5]); $n1 = new Node(1, [$n2,$n3]); $t = new Tree($n1); $expected = [1,2,4,3,5]; $this->assertEquals($expected, $t->dfs()); } }

Trees

Create tree.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <?php class Tree { function __construct($root = null) { $this->root = $root; } public function bfs() { // 1. shift val // 2. if children, append to arr // 3. append data to array to compare if ($this->root == null) { throw new Error("No tree root"); } $arr = array($this->root); $res = []; while (count($arr) > 0) { $x = array_shift($arr); if ($x->children != null) { $arr = array_merge($arr, $x->children); } array_push($res, $x->data); } return $res; } public function dfs() { // shift from arr // if children exist, unshift array // add data to res array $res = []; $arr = array($this->root); while (count($arr) > 0) { $x = array_shift($arr); if ($x->children != null) { $arr = array_merge($x->children, $arr); } array_push($res, $x->data); } return $res; } } class Node { function __construct($data = null, $children = null) { $this->data = $data; $this->children = $children; } }

Running Tests

Change into directory and run phpunit.phar tree_test.php.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.