1. 题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
2. 题解
1、我的提交
使用自底向上的递归,并且先遍历右子树,再遍历左子树。
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return root;
}
helper(root);
return root;
}
//自底向上的遍历
private void helper(TreeNode root){
if(root == null){
return;
}
//右
helper(root.right);
//左
helper(root.left);
//左右交换
TreeNode temp = new TreeNode(0);
if(root.left != null){
temp = root.left;
if(root.right != null){
// left!=null, right!=null
root.left = root.right;
root.right = temp;
}else{
// left!=null, right==null
root.right = temp;
root.left = null;
}
}else{
if(root.right != null){
// left==null, right!=null
root.left = root.right;
root.right = null;
}
}
}
}
时间复杂度:O(n),全部节点需要遍历一遍
空间复杂度:O(n),当树退化为链表时需要栈空间O(n)。
2、更简洁的递归代码
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode temp = root.left;
//遍历右,作为左节点返回
root.left = mirrorTree(root.right);
//遍历左,作为右节点返回
root.right = mirrorTree(temp);
return root;
}
}