(二叉树,递归) O(n)
递归遍历原树的所有节点,将每个节点的左右儿子互换即可。
C++代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void mirror(TreeNode* root) {
if (!root) return;
mirror(root->left);
mirror(root->right);
swap(root->left, root->right);
}
};
Java代码
Java没有自带的swap,需要自己实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void mirror(TreeNode root) {
if (root == null) return;
mirror(root.left);
mirror(root.right);
swap(root);
}
private static void swap(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
剑指 Offer 27. 二叉树的镜像
力扣原题需要返回值,为空时需要改一下,并且返回root
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (root == nullptr) return nullptr;
mirrorTree(root->left);
mirrorTree(root->right);
swap(root->left, root->right);
return root;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root == null) return null;
mirrorTree(root.left);
mirrorTree(root.right);
swap(root);
return root;
}
private static void swap(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}