fork download
  1. <?php
  2.  
  3. class Document
  4. {
  5.  
  6. private $_children = [];
  7.  
  8. public function parentLevel ()
  9. {
  10. $level = 0;
  11.  
  12. if ($this->hasChildren())
  13. {
  14. $childrenLevels = [];
  15.  
  16. foreach($this->children() as $child)
  17. {
  18. $childrenLevels[] = $child->parentLevel();
  19. }
  20.  
  21. $level = max($childrenLevels) + 1;
  22. }
  23.  
  24. return $level;
  25. }
  26.  
  27. public function children ()
  28. {
  29. return $this->_children;
  30. }
  31.  
  32. public function hasChildren ()
  33. {
  34. return (count($this->_children) > 0);
  35. }
  36.  
  37. public function addChild ($child)
  38. {
  39. $this->_children[] = $child;
  40. }
  41.  
  42. }
  43.  
  44. $doc1 = new Document();
  45. $doc2 = new Document();
  46. $doc3 = new Document();
  47. $doc4 = new Document();
  48. $doc5 = new Document();
  49. $doc6 = new Document();
  50. $doc7 = new Document();
  51.  
  52. $doc1->addChild($doc2);
  53. $doc1->addChild($doc3);
  54. $doc1->addChild($doc4);
  55.  
  56. $doc2->addChild($doc5);
  57. $doc2->addChild($doc6);
  58.  
  59. $doc5->addChild($doc7);
  60.  
  61. echo $doc1->parentLevel(), PHP_EOL;
Success #stdin #stdout 0.01s 82880KB
stdin
Standard input is empty
stdout
3