· 1 min read

Blind 75 - Invert Binary Tree

Swap left and right. Then repeat for those nodes.

[Video]

[Problem explanation in English]

Link

Intuition: Swap left and right. Then repeat for those nodes.

2 lines can be saved by using a single temporary variable instead of left & right, but this is clean.

O(n) time. O(1) space

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

Back to Blog