Site Search:

Self-Symmetric Binary Tree

Problem

Self-Symmetric Binary 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

Solution

If the input is an array, we can exam length 2 subarray, then length 4 subarray, then length 8 subarray, until we find a mismatch or exausted all the array elements.

[1,2,2,3,4,4,3]
 0
   1 2          = 1
       3     6  = 3
   l r l=r+1 r=l + 2^2 - 1
[1,2,2,0,3,0,3]

If the input is a tree, we can do post order recursive comparison.

public class SymmetricBST {
  public static boolean isSymmetric(int[] a) {
    int left = 0;
    int right = 0;
    int space = 1;
    int N = a.length; //7
    while(left < N && right < N) {
      int tmpleft = left;
      int tmpright = right;
      while(tmpleft < tmpright) { //
        if(a[tmpleft++] != a[tmpright--])
          return false;
      }
      left = right + 1; //3
      space = space * 2;  //4
      right = left + space - 1; //6
    }
    return true;
  }

  private class Node {
    int val;
    Node left, right;
  }

  public boolean isSymmetric(Node root) {
    return root == null || checkSymmetric(root.left, root.right);
  }

  // Deep-First Search (Pre-Order Traversal)
  private boolean checkSymmetric(Node left, Node right) {
    if (left == null && right == null)
      return true;
    if (left != null && right != null) {
      return left.val == right.val && checkSymmetric(left.left, right.right) && checkSymmetric(left.right, right.left);
    }
    return false;
  }

  public static void main(String... args) {
    int[] a = new int[]{1,2,2,3,4,4,3};
    System.out.println(isSymmetric(a));
    a = new int[]{1,2,2,0,3,0,3};
    System.out.println(isSymmetric(a));
  }
}


The function takes an array has time complexity O(N), because we need to exam all the elements in the array, the extra space is O(1).
The function takes a root node has time complexity O(N), the extra space is proportional to the depth of the caller stack, which is equal to the height of the tree O(H). H range from logN to N.