翻转二叉树
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/invert-binary-tree
解题思路
递归法: 主要是遍历一下二叉树,将左边的值赋值给右边,遍历完也是交换完了。
迭代法: 将二叉树压入队列,然后循环队列,一个个节点弹出来,每个节点交换左右子树的值,迭代完毕也是交换完毕
php 递归法代码
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return TreeNode
*/
function invertTree($root) {
if ($root == null) return null;
// 保存右子树
$rightTree = $root->right;
// 交换左右子树的位置
$root->right = $this->invertTree($root->left);
$root->left = $this->invertTree($rightTree);
return $root;
}
}
php 迭代法代码
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return TreeNode
*/
function invertTree($root) {
if ($root == null) return null;
$queue = new SplQueue();
$queue->enqueue($root);
while (!$queue->isEmpty()) {
$node = $queue->dequeue();
list($node->left, $node->right) = [$node->right, $node->left];
if ($node->left) {
$queue->enqueue($node->left);
}
if ($node->right) {
$queue->enqueue($node->right);
}
}
return $root;
}
}