Invert Binary Tree

Invert a binary tree.

Screen Shot 2016-04-01 at 2.58.13 PM.png to Screen Shot 2016-04-01 at 2.58.55 PM

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        
        if (root == null)
            return null;
        if ( (root.left == null) && (root.right == null)) {
            return root;
        } else if ((root.left != null) && (root.right != null)) {
            TreeNode temp; 
            temp = root.left; 
            root.left = root. right;
            root.right = temp; 
        } else if ((root.left != null) && (root.right == null)) {
            root.right = root.left; 
            root.left = null;
        } else if ((root.left == null) && (root.right != null)) {
            root.left = root.right; 
            root.right = null;
        }
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

Simpler version

public TreeNode invertTree(TreeNode root)  
{  
    if (root==null)  
    {  
        return null;  
    }  
    TreeNode left=root.left;  
    TreeNode right=root.right;  
    root.left=invertTree(right);  
    root.right=invertTree(left);  
    return root;  
}  
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