3v4l.org

run code in 300+ PHP versions simultaneously
<?php // Tree data structure class BinaryNode { public $value = null; // node value public $left = null; // left child public $right = null; // right child public function __construct($value) { $this->value = $value; } } /** * invertTree function goes here */ function invertTree($node) { if($node == null){ return null; } $left = invertTree($node->left); $right = invertTree($node->right); $node->left = $right; $node->right = $left; return $node; } $root = new BinaryNode(1); $rootLeftChild = new BinaryNode(2); $rootRightChild = new BinaryNode(3); $rootLeftChildLeftChild = new BinaryNode(4); $rootLeftChildRightNode = new BinaryNode(5); $rootRightChildLeftChild = new BinaryNode(6); $rootRightChildRightNode = new BinaryNode(7); $rootLeftChild->left = $rootLeftChildLeftChild; $rootLeftChild->right = $rootLeftChildRightNode; $rootRightChild->left = $rootRightChildLeftChild; $rootRightChild->right = $rootRightChildRightNode; $root->left = $rootLeftChild; $root->right = $rootRightChild; $invertedTree = invertTree($root); var_dump($invertedTree->value == 1); var_dump($invertedTree->left->value == 3); var_dump($invertedTree->right->value == 2); var_dump($invertedTree->left->left->value == 7); var_dump($invertedTree->left->right->value == 8); var_dump($invertedTree->right->left->value == 5); var_dump($invertedTree->right->right->value == 4);

preferences:
57.43 ms | 402 KiB | 5 Q