时间:2021-07-01 10:21:17 帮助过:57人阅读
本文实例讲述了PHP获取二叉树镜像的方法。分享给大家供大家参考,具体如下:
问题
操作给定的二叉树,将其变换为源二叉树的镜像。
解决思路
翻转二叉树,有递归和非递归两种方式,非递归就是使用队列。
实现代码
- <?php
- /*class TreeNode{
- var $val;
- var $left = NULL;
- var $right = NULL;
- function __construct($val){
- $this->val = $val;
- }
- }*/
- function Mirror(&$root)
- {
- if($root == NULL)
- return 0;
- $queue = array();
- array_push($queue, $root);
- while(!empty($queue)){
- $node = array_shift($queue);
- $tmp = $node->left;
- $node->left = $node->right;
- $node->right = $tmp;
- if($node->left != NULL)
- array_push($queue, $node->left);
- if($node->right != NULL)
- array_push($queue, $node->right);
- }
- }
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》
希望本文所述对大家PHP程序设计有所帮助。