Back to home

Test FileTreesRunning Tests
PHP Binary Search Trees main image

PHP Binary Search Trees

This expects an installation on the system of phpunit.

Test File

Create binary-search-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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <?php require "binary-search-tree.php"; class BinarySearchTreeTest extends PHPUnit\Framework\TestCase { public function testInsert() { $n1 = new Node(5); $n1->insert(1); $n1->insert(3); $n1->insert(8); $this->assertEquals(1, $n1->left->data); $this->assertEquals(8, $n1->right->data); $this->assertEquals(3, $n1->left->right->data); } public function testContains() { $n1 = new Node(5); $n1->insert(1); $n1->insert(3); $n1->insert(8); $res = $n1->contains(8); $res2 = $n1->contains(10); $this->assertEquals(false, $res == null); $this->assertEquals(true, $res2 == null); } public function validate($node, $min=null, $max=null) { if ($max != null && $node->data > $max) { return false; } else if ($min != null && $node->data < $min) { return false; } if ($node->left != null && !$this->validate($node->left, $min, $node->data)) { return false; } if ($node->right != null && !$this->validate($node->right, $node->data, $max)) { return false; } return true; } public function testValidate() { $n1 = new Node(5); $n1->insert(1); $n1->insert(3); $n1->insert(8); $res = $this->validate($n1); $this->assertEquals(true, $res); } }

Trees

Create binary-search-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 <?php class Node { function __construct($data, $left=null, $right=null) { $this->data = $data; $this->left = $left; $this->right = $right; } public function insert($data) { if ($data < $this->data && $this->left) { return $this->left->insert($data); } else if ($data < $this->data && !$this->left) { return $this->left = new Node($data); } else if ($data > $this->data && $this->right) { return $this->right->insert($data); } else if ($data > $this->data && !$this->right) { return $this->right = new Node($data); } } public function contains($data) { if ($data == $this->data) { return $this; } else if ($data < $this->data && $this->left) { return $this->left->contains($data); } else if ($data > $this->data && $this->right) { return $this->right->contains($data); } } }

Running Tests

Change into directory and run phpunit.phar binary-search-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.