/**
* Given a binary tree, check whether it is a mirror of itself
* (ie, symmetric around its center).
* 1
* /
* 2 2
* / /
* 3 4 4 3
*
* 对于二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。
* 例如,此二叉树是对称的:
* 1
* /
* 2 2
* / /
* 3 4 4 3
*/
/** * Given a binary tree, check whether it is a mirror of itself * (ie, symmetric around its center). * 1 * / * 2 2 * / / * 3 4 4 3 * * 对于二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。 * 例如,此二叉树是对称的: * 1 * / * 2 2 * / / * 3 4 4 3 */ public class Main42 { public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(2); root.left.left = new TreeNode(3); root.right.right = new TreeNode(3); root.left.right = new TreeNode(5); root.right.left = new TreeNode(4); System.out.println(Main42.isSymmetric(root)); } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isEquals(root.left, root.right); } public static boolean isEquals(TreeNode root1, TreeNode root2) { if (root1 == null && root2 == null) { return true; } if (root1 == null || root2 == null) { return false; } if (root1.val != root2.val) { return false; } return isEquals(root1.left, root2.right) && isEquals(root1.right, root2.left); } }