将根节点左右子树看作两颗二叉树,对称的话就是对于对应的两个节点来说,我的左子节点等于你的右子节点,我的右子节点等于你的左子节点,递归判断每个节点是否符合。
临界条件:两个都为空,返回true,两个只有一个为空,返回false;
public class Solution { boolean isSymmetrical(TreeNode pRoot) { if(pRoot==null){ return true; } return help(pRoot.left,pRoot.right); } boolean help(TreeNode root1,TreeNode root2){ if(root1==null&&root2==null){ return true; } if(root1==null||root2==null){ return false; } return root1.val==root2.val&&help(root1.left,root2.right)&&help(root1.right,root2.left); } }