题目描述:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4 / \ 2 7 / \ / \ 1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例一:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
解题思路:
由上述题目可知,每个root有左右两个子节点,每个root的两个子节点都需要进行交换位置,可以想到,这是一个递归的过程,可以直接使用递归的方式进行解题,使用第三变量,使左右两个子节点进行交换即可。
代码如下:
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
TreeNode sb;
mirrorTree(root.right);
sb=root.right;
mirrorTree(root.left);
root.right=root.left;
root.left=sb;
return root;
}
}
欢迎大家提供更多解法。
题目来源:LeetCode
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。