问题描述:
Given the root of a binary tree, invert the tree, and return its root.
将二叉树镜像
思路:
发现子问题:将给定二叉树镜像相当于将其左子树和右子树分别镜像,然后交换左右子树指针
代码如下:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null) return null;
//交换左右子树
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
//左子树递归
invertTree(root.left);
//右子树递归
invertTree(root.right);
//返回根节点
return root;
}
}
时间复杂度:O(n)