解题思路:
1.如果根节点为空,那么对称;
2.如果根节点不为空,根节点的左子树为空,根节点的右子树不为空,或者根节点的左子树不为空,根节点的右子树为空,那么一定不对称;
3.如果根节点的左子树的值和右子树的值不相等,那么一定不对称;
4.如果上面条件都没有满足到,那么我们需要判断左子树的左子树是否和右子树的右子树相等,左子树的右子树是否和右子树的左子树相等,如果相等,则对称;
代码:
publicbooleanisSymmetric(TreeNoderoot) { if (root==null) { returntrue; } returnisSymmetricChild(root.left, root.right); } publicbooleanisSymmetricChild(TreeNodeleftTree, TreeNoderightTree) { if (leftTree==null&&rightTree==null) { returntrue; } if (leftTree!=null&&rightTree==null||leftTree==null&&rightTree!=null) { returnfalse; } if (leftTree.val!=rightTree.val) { returnfalse; } returnisSymmetricChild(leftTree.left, rightTree.right) &&isSymmetricChild(leftTree.right, rightTree.left); }