Symmetric Binary Tree

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

Example:

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

is a symmetric binary tree.

Solution:

Compare the left subtree and right subtree are mirrored or not.

Code:

public class Solution {

    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isMirror(root.left, root.right);
    }

    private boolean isMirror(TreeNode a, TreeNode b) {
        if (a == null && b == null) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        if (a.val != b.val) {
            return false;
        }
        return isMirror(a.left, b.right) && isMirror(a.right, b.left);
    }
}

results matching ""

    No results matching ""