题目
输入一个二叉树,将它变换为它的镜像。
样例
算法
(二叉树,递归) O(n)
我们可以发现镜像后的树就是将原树的所有节点的左右儿子互换!
所以我们递归遍历原树的所有节点,将每个节点的左右儿子互换即可。
时间复杂度
原树仅被遍历一次,所以时间复杂度是 O(n)。
class Solution {
public void mirror(TreeNode root) {
if(root == null) return ;
if(root.left != null || root.right != null ){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
if(root.left != null)
mirror(root.left);
if(root.right != null)
mirror(root.right);
}
}