题目描述
输入一个二叉树,将它变换为它的镜像。
样例
输入树:
8
/ \
6 10
/ \ / \
5 7 9 11
[8,6,10,5,7,9,11,null,null,null,null,null,null,null,null]
输出树:
8
/ \
10 6
/ \ / \
11 9 7 5
[8,10,6,11,9,7,5,null,null,null,null,null,null,null,null]
算法
(二叉树,递归) $O(n)$
仔细观察原树和镜像之后的树:
原树:
8
/ \
6 10
/ \ / \
5 7 9 11
镜像后的树:
8
/ \
10 6
/ \ / \
11 9 7 5
我们可以发现镜像后的树就是将原树的所有节点的左右儿子互换!
所以我们递归遍历原树的所有节点,将每个节点的左右儿子互换即可。
时间复杂度
原树仅被遍历一次,所以时间复杂度是 $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==NULL)return;
swap(root->left,root->right);
mirror(root->left);
mirror(root->right);
}
};
C 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void mirror(struct TreeNode* root) {
if(root==NULL)return;
struct TreeNode*t=root->left;
root->left=root->right;
root->right=t;
mirror(root->left);
mirror(root->right);
}
Java 代码
/**
* 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;
TreeNode t=root.left;
root.left=root.right;
root.right=t;
mirror(root.left);
mirror(root.right);
}
}
Python 代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirror(self, root):
"""
:type root: TreeNode
:rtype: void
"""
if root==None:
return
root.left,root.right=root.right,root.left
self.mirror(root.left)
self.mirror(root.right)
Javascript 代码
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {void}
*/
var mirror = function(root) {
if(root==null){
return;
}
var t=root.left;
root.left=root.right;
root.right=t;
mirror(root.left);
mirror(root.right);
};
Python3 代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirror(self, root):
"""
:type root: TreeNode
:rtype: void
"""
if root==None:
return
root.left,root.right=root.right,root.left
self.mirror(root.left)
self.mirror(root.right)
Go 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mirror(root *TreeNode) {
if root==nil{
return
}
root.Left,root.Right=root.Right,root.Left
mirror(root.Left)
mirror(root.Right)
}