当前位置:首页 > PHP教程 > PHP高级教程

PHP获取二叉树镜像的方法

本文实例讲述了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程序设计有所帮助。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!