给定一个二叉树,检查它是否是镜像对称的。
思路:
判断一棵树是不是对称的,可以看看左右子树是不是镜像关系
- 如果是空树,是对称
- 接着判断左右子树是不是对称的
2.1如果两个树都是空树,是镜像
2.2,如果一个空一个非空,不算镜像
2.3如果两棵树都不为空
a)比较根节点是否相同,不相同,不是镜像
b)递归比较子树,t1.left 和t2.right ,再看 t1.right和t2.left是不是相同
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isMirror(TreeNode t1,TreeNode t2){
if(t1 == null && t2 == null){
return true;
}
if(t1 == null || t2 == null){
return false;
}
if(t1.val != t2.val){
return false;
}
return isMirror(t1.left,t2.right)&& isMirror(t1.right,t2.left);
}
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return isMirror(root.left,root.right);
}
}
判断一棵树是不是对称
我们采用巧妙的镜像来解决,将一棵树分为左子树和右子树
旋转二叉树
题目网址:https://leetcode-cn.com/problems/invert-binary-tree/
如果我们想要得到一棵树的镜像
可以遍历+加交换,把每一个节点的左右子树都互换一下。
public TreeNode makeMirror(TreeNode root){
if(root == null){
return null;
}
//交换就是此处的 "访问"操作
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
makeMirror(root.left);
makeMirror(root.right);
return root;
}