Symmetric Tree – Recursion Solution

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

 


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) return true;
        
        return recursiveStep(root.left, root.right);
    }
    
    public static boolean recursiveStep(TreeNode left, TreeNode right) {
        
        if (left == null && right == null) return true;
        
        if (left != null && right != null && left.val == right.val && recursiveStep(left.left, right.right) && recursiveStep(left.right, right.left)) {
            return true;
        }
        
        return false;
        
    }
    
}
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