Skip to content

Commit 0705c73

Browse files
committed
Added binary tree example in PHP
1 parent 7b6c369 commit 0705c73

File tree

3 files changed

+112
-0
lines changed

3 files changed

+112
-0
lines changed

chap-06/binary-tree-example.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 6/10/18
6+
* Time: 15:13
7+
*/
8+
9+
use App\Chapter06\BinaryNode;
10+
use App\Chapter06\BinaryTree;
11+
12+
require_once __DIR__ . "/../vendor/autoload.php";
13+
14+
$final = new BinaryNode("Final");
15+
16+
$tree = new BinaryTree($final);
17+
18+
$semiFinal1 = new BinaryNode("Semi Final 1");
19+
$semiFinal2 = new BinaryNode("Semi Final 2");
20+
$quarterFinal1 = new BinaryNode("Quarter Final 1");
21+
$quarterFinal2 = new BinaryNode("Quarter Final 2");
22+
$quarterFinal3 = new BinaryNode("Quarter Final 3");
23+
$quarterFinal4 = new BinaryNode("Quarter Final 4");
24+
25+
$semiFinal1->addChildren($quarterFinal1,$quarterFinal2);
26+
$semiFinal2->addChildren($quarterFinal3,$quarterFinal4);
27+
28+
$final->addChildren($semiFinal1, $semiFinal2);
29+
30+
$tree->traverse($tree->root);

src/Chapter06/BinaryNode.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 6/10/18
6+
* Time: 13:52
7+
*/
8+
9+
namespace App\Chapter06;
10+
11+
12+
class BinaryNode
13+
{
14+
public $data;
15+
public $left;
16+
public $right;
17+
18+
/**
19+
* BinaryNode constructor.
20+
* @param $data
21+
*/
22+
public function __construct( string $data = NULL)
23+
{
24+
$this->data = $data;
25+
$this->left = NULL;
26+
$this->right = NULL;
27+
}
28+
29+
public function addChildren(BinaryNode $right, BinaryNode $left)
30+
{
31+
$this->left = $left;
32+
$this->right = $right;
33+
}
34+
35+
36+
}

src/Chapter06/BinaryTree.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 6/10/18
6+
* Time: 14:02
7+
*/
8+
9+
namespace App\Chapter06;
10+
11+
12+
class BinaryTree
13+
{
14+
public $root = NULL;
15+
16+
/**
17+
* BinaryTree constructor.
18+
* @param null $root
19+
*/
20+
public function __construct(BinaryNode $node)
21+
{
22+
$this->root = $node;
23+
}
24+
25+
/**
26+
* Traverse Binary Tree recursively.
27+
* @param BinaryNode $node
28+
* @param int $level
29+
*/
30+
public function traverse(BinaryNode $node, int $level = 0)
31+
{
32+
if ($node){
33+
echo str_repeat("-" ,$level);
34+
echo $node->data . PHP_EOL;
35+
36+
if ($node->right) {
37+
$this->traverse($node->right, $level + 1);
38+
}
39+
if ($node->left) {
40+
$this->traverse($node->left, $level + 1);
41+
}
42+
}
43+
}
44+
45+
46+
}

0 commit comments

Comments
 (0)