Recursive
/**
* 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) {
if (root == null) {
return true;
}
return helper(root.left, root.right);
}
private boolean helper(TreeNode leftRoot, TreeNode rightRoot) {
// if both of them are empty
if (leftRoot == null && rightRoot == null) {
return true;
}
// if one of them is not empty
if (leftRoot == null || rightRoot == null) {
return false;
}
// if they are not equal
if (leftRoot.val != rightRoot.val) {
return false;
}
return helper(leftRoot.left, rightRoot.right) && helper(leftRoot.right, rightRoot.left);
}
}
Iterative
/**
* 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) {
if (root == null) {
return true;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.addLast(root.left);
queue.addLast(root.right);
while (!queue.isEmpty()) {
TreeNode leftRoot = queue.removeFirst();
TreeNode rightRoot = queue.removeFirst();
// if both of them are empty, ignore the rest code of this round
if (leftRoot == null && rightRoot == null) {
continue;
}
// if one of the sub-tree is not empty
if (leftRoot == null || rightRoot == null) {
return false;
}
// if they are not equal
if (leftRoot.val != rightRoot.val) {
return false;
}
queue.addLast(leftRoot.left);
queue.addLast(rightRoot.right);
queue.addLast(rightRoot.left);
queue.addLast(leftRoot.right);
}
return true;
}
}