← Trees

Symmetric Tree

Easy
Python
def is_symmetric(root):
    def check(a,b):
        if not a and not b: return True
        if not a or not b: return False
        return a.val==b.val and check(a.left,b.right) and check(a.right,b.left)
    return check(root.left,root.right)
Java
public boolean isSymmetric(TreeNode root){
    return check(root.left,root.right);
}
boolean check(TreeNode a,TreeNode b){
    if(a==null&&b==null) return true;
    if(a==null||b==null) return false;
    return a.val==b.val&&check(a.left,b.right)&&check(a.right,b.left);
}

Key Insight

Nested function vs helper. Mirror comparison identical.

Python → Java Differences

  • Nested function vs helper method
  • 'not a' vs a==null
  • Mirror recursion identical
Python
def is_symmetric(root):
    def check(a,b):
        if not a and not b: return True
        if not a or not b: return False
        return a.val==b.val and check(a.left,b.right) and check(a.right,b.left)
    return check(root.left,root.right)
Java
public boolean isSymmetric(TreeNode root){
    return check(root.left,root.right);
}
boolean check(TreeNode a,TreeNode b){
    if(a==null&&b==null) return true;
    if(a==null||b==null) return false;
    return a.val==b.val&&check(a.left,b.right)&&check(a.right,b.left);
}

Algorithm Steps

1. Check as mirrors
2. left.left vs right.right
3. left.right vs right.left