Home > Article > Backend Development > How to implement mirror binary tree in php (code)
The content of this article is about how to implement mirrored binary tree (code) in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Operate the given binary tree and transform it into a mirror image of the source binary tree.
Mirror definition of binary tree: Source binary tree
Mirror binary tree Assign temp
2. Assign temp to the right subtree3. Assign the right subtree to the left subtree4. Recursion
mirror(root) temp=root->left root->left=root->right root-right=temp mirror(root->left) mirror(root->right)
class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } } function Mirror(&$root){ if($root==null){ return null; } $temp=$root->left; $root->left=$root->right; $root->right=$temp; Mirror($root->left); Mirror($root->right); } //构造一个树 $node5=new TreeNode(5); $node7=new TreeNode(7); $node9=new TreeNode(9); $node11=new TreeNode(11); $node6=new TreeNode(6); $node10=new TreeNode(10); $node8=new TreeNode(8); $node8->left=$node6; $node8->right=$node10; $node6->left=$node5; $node6->right=$node7; $node10->left=$node9; $node10->right=$node11; $tree=$node8; //镜像这棵二叉树 var_dump($tree); Mirror($tree); var_dump($tree);
object(TreeNode)#7 (3) { ["val"]=> int(8) ["left"]=> object(TreeNode)#5 (3) { ["val"]=> int(6) ["left"]=> object(TreeNode)#1 (3) { ["val"]=> int(5) ["left"]=> NULL ["right"]=> NULL } ["right"]=> object(TreeNode)#2 (3) { ["val"]=> int(7) ["left"]=> NULL ["right"]=> NULL } } ["right"]=> object(TreeNode)#6 (3) { ["val"]=> int(10) ["left"]=> object(TreeNode)#3 (3) { ["val"]=> int(9) ["left"]=> NULL ["right"]=> NULL } ["right"]=> object(TreeNode)#4 (3) { ["val"]=> int(11) ["left"]=> NULL ["right"]=> NULL } } object(TreeNode)#7 (3) { ["val"]=> int(8) ["left"]=> object(TreeNode)#6 (3) { ["val"]=> int(10) ["left"]=> object(TreeNode)#4 (3) { ["val"]=> int(11) ["left"]=> NULL ["right"]=> NULL } ["right"]=> object(TreeNode)#3 (3) { ["val"]=> int(9) ["left"]=> NULL ["right"]=> NULL } } ["right"]=> object(TreeNode)#5 (3) { ["val"]=> int(6) ["left"]=> object(TreeNode)#2 (3) { ["val"]=> int(7) ["left"]=> NULL ["right"]=> NULL } ["right"]=> object(TreeNode)#1 (3) { ["val"]=> int(5) ["left"]=> NULL ["right"]=> NULL } } }
The above is the detailed content of How to implement mirror binary tree in php (code). For more information, please follow other related articles on the PHP Chinese website!