原题: https://leetcode-cn.com/problems/symmetric-tree/
一、题目要求
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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 com.leetcode.test.tree;
/**
* 对称二叉树
*/
public class Solution2 {
public static void main(String[] args) {
TreeNode a1 = new TreeNode(1);
TreeNode a2 = new TreeNode(2);
TreeNode a3 = new TreeNode(2);
TreeNode a4 = new TreeNode(3);
TreeNode a5 = new TreeNode(4);
TreeNode a6 = new TreeNode(4);
TreeNode a7 = new TreeNode(3);
a1.left = a2;
a1.right = a3;
a2.left = a4;
a2.right = a5;
a3.left = a6;
a3.right = a7;
System.out.println(isSymmetric(a1));
}
public static boolean isSymmetric(TreeNode root) {
return isSame(root, root);
}
public static boolean isSame(TreeNode p, TreeNode q){
if (p == null && q == null){
return true;
}
if (p == null || q == null){
return false;
}
if (p.val != q.val){
return false;
}
return isSame(p.left, q.right) && isSame(p.right, q.left);
}
}