[PHP] 算法-镜像二叉树的PHP实现
程序员文章站
2022-06-05 22:04:33
操作给定的二叉树,将其变换为源二叉树的镜像。 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / ... ......
操作给定的二叉树,将其变换为源二叉树的镜像。 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5 思路: 1.左子树赋给temp 2.temp赋给右子树 3.右子树赋给左子树 4.递归 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 } } }