/**
* 对称二叉树
* 给定一个二叉树,检查它是否是镜像对称的。
* 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
*/
public class IsSymmetric {
public static boolean check(TreeNode p, TreeNode q){
//对比根节点是否相同
if(p == null && q == null){
return true;
}
if(p == null || q == null){
return false;
}
//对比根节点和左节点右节点是否相同,
// 这里左边的左节点对应右边的右节点,左边的右节点对应右边的左节点,镜像对称
return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
}
public static void main(String[] args){
TreeNode root = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(2);
TreeNode left01 = new TreeNode(3);
TreeNode right01 = new TreeNode(4);
TreeNode left02 = new TreeNode(4);
TreeNode right02 = new TreeNode(3);
root.left = left;
root.right = right;
left.left = left01;
left.right = right01;
right.left = left02;
right.right = right02;
System.out.println(check(root, root));
}
}
//* Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}