fork(1) download
  1. <?php
  2.  
  3. class Nexus
  4. {
  5. public $parent;
  6. public $leftChild;
  7. public $rightChild;
  8.  
  9. public function reverseChilds()
  10. {
  11. $temp = $this->leftChild;
  12. $this->leftChild = $this->rightChild;
  13. $this->rightChild = $temp;
  14. }
  15.  
  16. public function createChilds()
  17. {
  18. $this->leftChild = new Nexus($this);
  19. $this->rightChild = new Nexus($this);
  20. }
  21.  
  22. public function __construct($parent = null)
  23. {
  24. $this->parent = $parent;
  25. }
  26. }
  27.  
  28. function buildATree(Nexus $base, $depth = 3, $i = 0)
  29. {
  30. $base->createChilds();
  31.  
  32. if ($i < $depth) {
  33. $i++;
  34. $base->leftChild = buildATree($base->leftChild, $depth, $i);
  35. $base->rightChild = buildATree($base->rightChild, $depth, $i);
  36. return $base;
  37. }
  38. }
  39.  
  40. function reverseAllChildsInTree(Nexus $base)
  41. {
  42. if (!empty($base->leftChild) && !empty($base->rightChild)) {
  43. $base->reverseChilds();
  44. $base->leftChild = reverseAllChildsInTree($base->leftChild);
  45. $base->rightChild = reverseAllChildsInTree($base->rightChild);
  46. }
  47. return $base;
  48. }
  49.  
  50. $topNexus = new Nexus();
  51. $topNexus = buildATree($topNexus);
  52. //var_dump($topNexus);
  53. $topNexus = reverseAllChildsInTree($topNexus);
  54. var_dump($topNexus);
Success #stdin #stdout 0.02s 52472KB
stdin
Standard input is empty
stdout
object(Nexus)#1 (3) {
  ["parent"]=>
  NULL
  ["leftChild"]=>
  object(Nexus)#3 (3) {
    ["parent"]=>
    *RECURSION*
    ["leftChild"]=>
    object(Nexus)#19 (3) {
      ["parent"]=>
      *RECURSION*
      ["leftChild"]=>
      NULL
      ["rightChild"]=>
      NULL
    }
    ["rightChild"]=>
    object(Nexus)#18 (3) {
      ["parent"]=>
      *RECURSION*
      ["leftChild"]=>
      NULL
      ["rightChild"]=>
      NULL
    }
  }
  ["rightChild"]=>
  object(Nexus)#2 (3) {
    ["parent"]=>
    *RECURSION*
    ["leftChild"]=>
    object(Nexus)#5 (3) {
      ["parent"]=>
      *RECURSION*
      ["leftChild"]=>
      NULL
      ["rightChild"]=>
      NULL
    }
    ["rightChild"]=>
    object(Nexus)#4 (3) {
      ["parent"]=>
      *RECURSION*
      ["leftChild"]=>
      NULL
      ["rightChild"]=>
      NULL
    }
  }
}