guys, I have this problem in PHP I'm trying to invert Binary Tree in PHP but I don't have an idea how to resolve this problem.
The task is to invert a binary tree, so the leaf's order is inverted.
Example:
1
/ \
2 3
/ \ / \
4 5 6 7
inverts to:
1
/ \
3 2
/ \ / \
7 6 5 4
Note: keep in mind that a tree can also be imbalanced.
/**
* leaf data structure
*/
class BinaryNode {
/** @var mixed null */
public $value = null;
/** @var BinaryNode null */
public $left = null;
/** @var BinaryNode null */
public $right = null;
/**
* @param mixed $value
*/
public function __construct( $value ) {
$this->value = $value;
}
}
class BinaryTree
{
/**
* @param BinaryNode $root
* @return BinaryNode
*/
public static function invert($root): BinaryNode
{
//$BinaryNode = new BinaryNode();
if(!isset($root)) return $root;
$tempLeftNode = $root->left;
$root->left = $root->right;
$root->right = $tempLeftNode;
self::invert($root->left);
self::invert($root->right);
return $root;
}
}
$root = new BinaryNode(1);
$root->left = new BinaryNode(2);
$root->right = new BinaryNode(3);
$root->left->left = new BinaryNode(4);
$root->left->right = new BinaryNode(5);
$root->right->left = new BinaryNode(6);
$root->right->right = new BinaryNode(7);
print_r(BinaryTree::invert($root));
invertfunction returnsnullon leaves but this is disallowed by your return type, so consider fixing that to compile--if you remove the return type specifier, your code produces your desired output.