|
| 1 | +<?php |
| 2 | + |
| 3 | + |
| 4 | +/** |
| 5 | + * DevCafe Solutions Limited operates as a software development company with the following role hierarchy. |
| 6 | +CEO |
| 7 | +-CTO |
| 8 | +--Senior Architect |
| 9 | +---Software Engineer |
| 10 | +--Quality Assurance Engineer |
| 11 | +--User Interface Designer |
| 12 | +-CFO |
| 13 | +-CMO |
| 14 | +-COO |
| 15 | +
|
| 16 | +
|
| 17 | + * Question: |
| 18 | + * Given the role above, design a tree data structure that mimics this organization structure |
| 19 | + * |
| 20 | + * |
| 21 | + */ |
| 22 | + |
| 23 | +class TreeNode |
| 24 | +{ |
| 25 | + public $data = null; |
| 26 | + public $children = []; |
| 27 | + public function __construct(string $data = null) |
| 28 | + { |
| 29 | + $this->data = $data; |
| 30 | + } |
| 31 | + public function addChildren(TreeNode $node) |
| 32 | + { |
| 33 | + $this->children[] = $node; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class Tree |
| 38 | +{ |
| 39 | + public $root = null; |
| 40 | + public function __construct(TreeNode $node) |
| 41 | + { |
| 42 | + $this->root = $node; |
| 43 | + } |
| 44 | + public function traverse(TreeNode $node, int $level = 0) |
| 45 | + { |
| 46 | + if ($node) { |
| 47 | + echo str_repeat("-", $level); |
| 48 | + echo $node->data . "\n"; |
| 49 | + foreach ($node->children as $childNode) { |
| 50 | + $this->traverse($childNode, $level + 1); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +$ceo = new TreeNode("CEO"); |
| 57 | +$cto = new TreeNode("CTO"); |
| 58 | +$cfo = new TreeNode("CFO"); |
| 59 | +$cmo = new TreeNode("CMO"); |
| 60 | +$coo = new TreeNode("COO"); |
| 61 | +$seniorArchitect = new TreeNode("Senior Architect"); |
| 62 | +$softwareEngineer = new TreeNode("Software Engineer"); |
| 63 | +$userInterfaceDesigner = new TreeNode("User Interface Designer"); |
| 64 | +$qualityAssuranceEngineer = new TreeNode("Quality Assurance Engineer"); |
| 65 | + |
| 66 | + |
| 67 | +$ceo->addChildren($cto); |
| 68 | +$ceo->addChildren($cfo); |
| 69 | +$ceo->addChildren($cmo); |
| 70 | +$ceo->addChildren($coo); |
| 71 | +$cto->addChildren($seniorArchitect); |
| 72 | +$seniorArchitect->addChildren($softwareEngineer); |
| 73 | +$cto->addChildren($qualityAssuranceEngineer); |
| 74 | +$cto->addChildren($userInterfaceDesigner); |
| 75 | + |
| 76 | +$tree = new Tree($ceo); |
| 77 | +$tree->traverse($tree->root); |
0 commit comments