代码:
public boolean isSymmetric(TreeNode root) { // 非空判断 if (root == null) { return true; } return isSymmetry(root.left,root.right); } public boolean isSymmetry(TreeNode left,TreeNode right) { // 都为空则相同返回true if (left == null && right == null) { return true; // 都不为空,判断两边是否相等,相等继续判断,不相等返回false } else if (left != null && right != null){ if (left.val == right.val) { return isSymmetry(left.left, right.right) && isSymmetry(left.right, right.left); } else { return false; } // 一个空一个非空两个必然不相等 } else { return false; } }
执行结果: