问题描述:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
上代码,拿去即可运行:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TreeNode {
private Integer val;
private TreeNode left;
private TreeNode right;
public TreeNode(Integer val) {
this.val=val;
}
}
public class Test03 {
public static void main(String[] args) {
TreeNode treeNode1 = new TreeNode(5);
TreeNode treeNode2 = new TreeNode(1);
TreeNode treeNode3 = new TreeNode(2);
treeNode1.setLeft(treeNode2);
treeNode1.setRight(treeNode3);
System.out.println(isMirror(treeNode1.getLeft(),treeNode1.getRight()));
}
public static boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.getVal() == t2.getVal())
&& isMirror(t1.getRight(), t2.getLeft())
&& isMirror(t1.getLeft(), t2.getRight());
}
}
运行结果:
我要刷100道算法题,第98道