请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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]
思路:这两棵树,可以看到根节点是相同的,它的左右节点互换了位置,交换位置后,下来左右节点的左右子节点也交换了位置,,,,,一直到节点是叶子节点,完成交换。
所以节点的遍历方式是前序遍历,遍历到的节点如果有子节点,即交换它的左右节点,当遍历完交换完所有非叶子节点时,得到这棵树的镜像。
注意,考虑边界情况,如果树为空,返回空,如果树只有一个节点,返回这个根节点。
代码:
/**
* 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;
}
if(root.left==null&& root.right==null){
return root;
}
//交换左右节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
mirrorTree(root.left);//前序遍历,递归
mirrorTree(root.right);//前序遍历,递归
return root;
}
}