Symmetric Tree

Symmetric Tree - If a tree cut from the centre  of root and fold them so it should be same,  like in first example 1 if tree cut into 2 parts and then fold it over each other so 2 will come over 2, 4 will over 4 and 3 will over 4, but in case of second example left side 2 has one right child that is 3 and left is null, and right 2 has right child 3 and left is null so it will overlap to null

like      1
        /   -  \
      2    -    2
    /   \   -   /   \
null  3  - null  3

so here left null will overlap 3  and 3 will overlap null.

---------------------------------------------------------------------------------------------

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

Example 1 : this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3


Example 2 : But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3




class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymetric(root.left, root.right);
    }
      
    public boolean isSymetric(TreeNode left, TreeNode right){
        if(left == null && right == null) return true;
        else if(left != null && right != null){
            return left.val == right.val &&
                        isSymetric(right.right, left.left) && 
                        isSymetric(right.left, left.right);
        }
        return false;
    }
}





Post a Comment

Previous Post Next Post