Invert Binary Tree

Sneha Michelle,TreesRecursion

Problem Link

Invert a Binary Tree (opens in a new tab)

Problem Statement


Algorithm

A main part about trees is recursions. We need to swap the elements of each node on each level.

Code

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root==null){
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        return root;
    }
}