题目:
分析:先理解好镜像的概念再去思考怎么做题。这道题还是比较容易想到用递归的,比较两棵树,剩下的就是思考递归怎么结束
有几个条件,1.两棵子树都是空的,2.有一棵子树是空的,3.两个树节点的值不相等
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return isSymmetric(root.left,root.right);
}
boolean isSymmetric(TreeNode n1, TreeNode n2){
if(n1 == null && n2 == null){
return true;
}
//有一个为空了说明左右长度不等,一定不是镜像
if(n1 == null || n2 == null){
return false;
}
if(n1.val != n2.val){
return false;
}
return isSymmetric(n1.left,n2.right) && isSymmetric(n1.right, n2.left);
}
}