本文实例讲述了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获取链表中倒数第k个节点的方法讲解
php实现从上往下打印二叉树的方法讲解
php通过header发送自定义数据方法_php技巧
以上就是php获取二叉树镜像的方法讲解的详细内容。
