<?php
error_reporting(-1);
 
class Nexus
{
	public $parent;
	public $leftChild;
	public $rightChild;
 
	public function reverseChilds()
	{
		$temp = $this->leftChild;
		$this->leftChild = $this->rightChild;
		$this->rightChild = $temp;
	}
 
    public function createChilds()
    {
        $this->leftChild = new Nexus($this);
        $this->rightChild = new Nexus($this);
    }
 
	public function __construct($parent = null)
	{
		$this->parent = $parent;
	}
}
 
function buildATree(Nexus $base, $depth = 3, $i = 0)
{
	$base->createChilds();
 
	if ($i < $depth) {
		$i++;
		$base->leftChild = buildATree($base->leftChild, $depth, $i);
		$base->rightChild = buildATree($base->rightChild, $depth, $i);
		return $base;
	}
}
 
function reverseAllChildsInTree(Nexus $base)
{
	if (!empty($base->leftChild) && !empty($base->rightChild)) {
		$base->reverseChilds();
		$base->leftChild = reverseAllChildsInTree($base->leftChild);
		$base->rightChild = reverseAllChildsInTree($base->rightChild);
	}
	return $base;
}
 
$topNexus = new Nexus();
$topNexus = buildATree($topNexus);
//var_dump($topNexus);
$topNexus = reverseAllChildsInTree($topNexus);
var_dump($topNexus);