Posts Invert Binary Tree
Post
Cancel

Invert Binary Tree

PROBLEM DESCRIPTION

Invert the binary tree by swapping every every left node in the tree with its right node.

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.*;

class Program {
  public static void invertBinaryTree(BinaryTree tree) {

    if(tree == null) return;

    BinaryTree temp = tree.left;
    tree.left = tree.right;
    tree.right = temp;
    
    invertBinaryTree(tree.left);
    invertBinaryTree(tree.right);
 
  }

  static class BinaryTree {
    public int value;
    public BinaryTree left;
    public BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
    }
  }
}

Another way to code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;

class Program {
  public static void invertBinaryTree(BinaryTree tree) {
    invertHelper(tree);
  }

  public static BinaryTree invertHelper(BinaryTree tree){
    
    if(tree == null) return null;

    BinaryTree temp = tree.left;
    
    tree.left = invertHelper(tree.right);
    tree.right = invertHelper(temp);

    return tree;
  }
}
This post is licensed under CC BY 4.0 by the author.