File tree Expand file tree Collapse file tree 3 files changed +112
-0
lines changed Expand file tree Collapse file tree 3 files changed +112
-0
lines changed Original file line number Diff line number Diff line change
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 );
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments