### 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.

Example:

# 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) {
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);

}
}
```

Other Posts You May Like