当前位置:Gxlcms > PHP教程 > PHP获取二叉树镜像的方法

PHP获取二叉树镜像的方法

时间:2021-07-01 10:21:17 帮助过:57人阅读

本文实例讲述了PHP获取二叉树镜像的方法。分享给大家供大家参考,具体如下:

问题

操作给定的二叉树,将其变换为源二叉树的镜像。

解决思路

翻转二叉树,有递归和非递归两种方式,非递归就是使用队列。

实现代码

  1. <?php
  2. /*class TreeNode{
  3. var $val;
  4. var $left = NULL;
  5. var $right = NULL;
  6. function __construct($val){
  7. $this->val = $val;
  8. }
  9. }*/
  10. function Mirror(&$root)
  11. {
  12. if($root == NULL)
  13. return 0;
  14. $queue = array();
  15. array_push($queue, $root);
  16. while(!empty($queue)){
  17. $node = array_shift($queue);
  18. $tmp = $node->left;
  19. $node->left = $node->right;
  20. $node->right = $tmp;
  21. if($node->left != NULL)
  22. array_push($queue, $node->left);
  23. if($node->right != NULL)
  24. array_push($queue, $node->right);
  25. }
  26. }

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》

希望本文所述对大家PHP程序设计有所帮助。

人气教程排行