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));
You can do it using a recursively function... I remember doing an exercise like this years ago... Well, my solution would be something like this:
$array = [
'a' => [
'b1' => [
'c1' => [
'e1' => 4,
'f1' => 5,
'g1' => 6,
],
'd1' => [
'e11' => 4,
'f11' => 5,
'g11' => 6,
]
],
'b2' => [
'c2' => [
'e2' => 4,
'f2' => 5,
'g2' => 6,
],
'd2' => [
'e21' => 4,
'f21' => 5,
'g21' => 6,
]
],
]
];
With the function:
function reverse_recursively($arrayInput) {
foreach ($arrayInput as $key => $input) {
if (is_array($input)) {
$arrayInput[$key] = reverse_recursively($input);
}
}
return array_reverse($arrayInput);
}
echo '<pre>';
print_r($array);
echo '<br>';
print_r(reverse_recursively($array));
And you can see the test here: https://3v4l.org/2pYhR
function invertTree($root) {
if($root == null)
return null;
$flag = $root->right;
$root->right = invertTree($root->left);
$root->left = invertTree($flag);
return $root;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.