Symmetric Tree

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

 /**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return compare2Trees (root.left, root.right);
}

public boolean compare2Trees (TreeNode root1, TreeNode root2) {
        if (root1 == null || root2 == null)  {
            if (root1 == null && root2 == null)
                return true;
            else
                return false;
        }
        if (root1.val != root2.val)
            return false;
        else {
            return compare2Trees (root1.left, root2.right) && compare2Trees (root1.right, root2.left);
        }
}

Comments: we should solve this problem recursively, which means we need to discuss the basic cases first. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s