将根树进行拆分遍历,左子树的右节点要与右子树的左节点相等。
下面是递归的做法:
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null)return true;
return check(root.left,root.right);
}
public boolean check(TreeNode rootLeft,TreeNode rootRight){
if(rootLeft==null&&rootRight==null)return true;
if(rootLeft==null||rootRight==null)return false;
//比较相同位置的值是否相等
if(rootLeft.val!=rootRight.val)return false;
//传入左子树的左节点,右子树的右节点
if(!check(rootLeft.left,rootRight.right))return false;
//传入左子树的右节点,右子树的左节点
if(!check(rootLeft.right,rootRight.left))return false;
return true;
}
}
题目来源:leetcode.com