/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return helper(root.left, root.right);
}
private boolean helper(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
return (p.val == q.val) && helper(p.left, q.right) && helper(p.right, q.left);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null || root.left == null && root.right == null) return true;
if (root.left == null || root.right == null) return false;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root.left);
queue.offer(root.right);
while (!queue.isEmpty()) {
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if (left.val != right.val) return false;
if (left.left != null && right.right != null) {
queue.offer(left.left);
queue.offer(right.right);
} else if (left.left == null && right.right != null || left.left != null && right.right == null) {
return false;
}
if (left.right != null && right.left != null) {
queue.offer(left.right);
queue.offer(right.left);
} else if (left.right != null && right.left == null || left.right == null && right.left != null) {
return false;
}
}
return true;
}
}