[PHP] 算法-镜像二叉树的PHP实现
2023-02-18 15:41:48 时间
操作给定的二叉树,将其变换为源二叉树的镜像。 二叉树的镜像定义:源二叉树 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 } } }
相关文章
- 性能调优命令之top
- mac及Windows系统禁止Chrome浏览器更新
- pip安装超时问题
- 爬虫学习--http请求详解
- Centos 配置eth0 提示Device does not seem to be present
- 判定表法测试用例设计
- 非关系型数据库(nosql)介绍
- 性能调优命令之vmstat
- 浅谈 DML、DDL、DCL的区别
- SQL优化
- Appium定位方式总结
- 移动端自动化测试-AppiumApi接口详解及常用adb命令
- 移动端自动化测试-WTF Appium?
- Selenium-Css Selector使用方法
- Selenium-Switch与SelectApi接口详解
- Selenium-ActionChains Api接口详解
- Selenium-WebDriverApi接口详解
- Selenium之前世今生
- Xpath使用方法
- Selenium-WebDriver驱动对照表