递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {val = x;}
* }
*/
class Solution {public boolean isSymmetric(TreeNode root) {return check(root, root);
}
public boolean check(TreeNode a, TreeNode b) {if(a == null && b == null) {return true;}
if(a == null || b == null) {return false;}
return a.val == b.val && check(a.left, b.right) && check(a.right, b.left);
}
}
迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {val = x;}
* }
*/
class Solution {public boolean isSymmetric(TreeNode root) {Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
queue.offer(root);
while(!queue.isEmpty()) {TreeNode a = queue.poll();
TreeNode b = queue.poll();
if(a==null && b==null){continue;}
if(a==null || b==null){return false;}
if(a.val != b.val) {return false;}
queue.offer(a.left);
queue.offer(b.right);
queue.offer(a.right);
queue.offer(b.left);
}
return true;
}
}