Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree`[1,2,2,3,4,4,3]`is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following`[1,2,2,null,3,null,3]`is not:
1
/ \
2 2
\ \
3 3
Note: Bonus points if you could solve it both recursively and iteratively.

Analysis

Recursive
Check left subtree and right subtree to see if they are mirrors of each other, also the value of root node should be the same.
(node1.val == node2.val) && isMirror(node1.left, node2.right) && isMirror(node1.right, node2.left);
Complexity Analysis
• Time complexity :O(n). Because we traverse the entire input tree once, the total run time is O(n), where n is the total number of nodes in the tree.
• Space complexity : The number of recursive calls is bound by the height of the tree. In the worst case, the tree is linear and the height is inO(n). Therefore, space complexity due to recursive calls on the stack is O(n) in the worst case.
Iterative
Use queue, when adding to the queue, put right and left children of two nodes in opposite order:
q.offer(t1.left);
q.offer(t2.right);
q.offer(t1.right);
q.offer(t2.left);
Complexity Analysis
• Time complexity :O(n). Because we traverse the entire input tree once, the total run time is O(n), where `n` is the total number of nodes in the tree.
• Space complexity : There is additional space required for the search queue. In the worst case, we have to insert O(n) nodes in the queue. Therefore, space complexity is O(n).

Solution

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) {
return root == null || isMirror(root.left, root.right);
}
boolean isMirror(TreeNode node1, TreeNode node2) {
if (node1 == null && node2 == null) return true;
if (node1 == null || node2 == null) return false;
if (node1.val != node2.val) return false;
return isMirror(node1.left, node2.right) && isMirror(node1.right, node2.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;
q.offer(root.left);
q.offer(root.right);
while (!q.isEmpty()) {
TreeNode n1 = q.poll();
TreeNode n2 = q.poll();
if (n1 == null && n2 == null) continue;
if (n1 == null && n2 != null) return false;
if (n1 != null && n2 == null) return false;
if (n1.val != n2.val) return false;
q.offer(n1.left);
q.offer(n2.right);
q.offer(n1.right);
q.offer(n2.left);
}
return true;
}
}