题意:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
二叉树镜像定义:
对于二叉树中任意节点 root,设其左 / 右子节点分别为 left, right ;则在二叉树的镜像中的对应 root节点,其左 / 右子节点分别为 right, left 。
就类似于,左右子树相互折叠,然后相向复制
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
思路:
交换每个节点的左右子树,即可生成二叉树的镜像
常用交换操作
这里用递归方法实现
首先判空。
1.初始化节点tmp,用于暂存root的左子节点
2.递归右子节点mirrorTree(root.right),并将返回值作为root的左子节点
3.递归左子节点mirrorTree(root.left),并将返回值作为root的右子节点
4.最后,返回当前节点root;
Java代码实现:
/**
* 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;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}