题目:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
思路:递归
package edu.LeetCode.对称的树;
public class Solution {
//判断是否是对称的树
public boolean isSymmetric(TreeNode root){
return isMirror(root,root);
}
//写一个函数判断此树是否是镜像对称(每个树的右子树是否与其左子树对称)
private boolean isMirror(TreeNode r1, TreeNode r2) {
//都为空则一定是对称的
if(r1 == null && r2 == null){
return true;
}
//只有一个为空则返回false
if(r1 == null || r2 == null){
return false;
} else{
//判断当前节点的值是否相等以及右子树与左子树是否相等
return (r1.val == r2.val)&&isMirror(r1.left,r2.right)&& isMirror(r1.right,r2.left);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode r1 = new TreeNode(2);
TreeNode r2 = new TreeNode(2);
TreeNode r3 = new TreeNode(3);
TreeNode r4 = new TreeNode(4);
TreeNode r5 = new TreeNode(4);
TreeNode r6 = new TreeNode(3);
root.left = r1;
root.right = r2;
r1.left = r3;
r1.right = r4;
r2.left = r5;
r2.right = r6;
Solution s = new Solution();
System.out.println(s.isSymmetric(root));
}
}