问题描述:
给定root
一棵二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。
示例:
思路:
首先根节点不会破坏镜面关系,其次根节点的左孩子的左(右)分支与右孩子的右(左)分支相同。
代码:
public class SymmetricTree {
public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
}
public static boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public static boolean isMirror(TreeNode h1, TreeNode h2) {
if (h1 == null ^ h2 == null) {
return false;
}
if (h1 == null && h2 == null) {
return true;
}
return h1.val == h2.val && isMirror(h1.left, h2.right) && isMirror(h1.right, h2.left);
}
}