题目
代码
方法一:递归法
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public 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);
}
}
方法二:迭代法
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(p);
queue.offer(q);
while(!queue.isEmpty()) {
TreeNode u = queue.poll();
TreeNode v = queue.poll();
if(u == null && v == null) {
continue;
}
if (u == null || v == null) {
return false;
} else if (u.val != v.val) {
return false;
}
queue.offer(u.left);
queue.offer(v.right);
queue.offer(u.right);
queue.offer(v.left);
}
return true;
}
}