Problem

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Examples

Example 1:

1
2
Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

1
2
3
4
5
    1
   / \
  2   2
   \   \
    3    3
1
2
Input: root = [1,2,2,null,3,null,3]
Output: false

Solution

Method 1 - Recursion

This problem can be solve by using a simple recursion. The key is finding the conditions that return false, such as value is not equal, only one node(left or right) has value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
	    return true;
	}
    return isSymmetric(root.left, root.right);
}

public boolean isSymmetric(TreeNode l, TreeNode r) {
    if (l == null && r == null) {
        return true;
    } else if (r == null || l == null) {
        return false;
    }

    return l.val == r.val && 
    isSymmetric(l.left, r.right) && 
    isSymmetric(l.right, r.left);
}