How to Invert Binary Tree Java - The Coding Shala

Home >> Interview Questions >> Invert Binary Tree
In this post, you will learn how to invert the binary tree and will implement a Java program to invert binary tree.

Invert Binary Tree

Invert the given Binary Tree.

Invert Binary Tree - The Coding Shala

Invert Binary Tree Java Solution

What does it mean to invert a binary tree? In a Binary Tree if we swap or interchanges all of its left and right children of all non-leaf nodes then it became an inverted binary tree.

Approach 1:
We can invert a binary tree using Recursion. We need to swap the left and right nodes of a root node and follow this step recursively for all the nodes.

Java Program: 
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
class Solution {
    public TreeNode invertTree(TreeNode root) {
        TreeNode head = root;
        if(root == null) return root;
        if(root.left == null && root.right == null) return root;
        TreeNode tmp = root.right;
        root.right = root.left;
        root.left = tmp;
        if(root.left != null ) invertTree(root.left);
        if(root.right != null ) invertTree(root.right);
        return head;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala