// Interview Study Guide (34 problems)

Invert a Binary Tree

Given a binary tree, write a method invertTree(Node root) which inverts the tree at each level.

Example

       10                     10
      /  \                   /  \
     5    15       ->       15   5
    / \    \               /    / \
   2   6    20            20   6   2

Solution

public void invertTree(TreeNode root) {
    if(root == null) return;

    TreeNode tmp = root.left;
    root.left = root.right;
    root.right = tmp;

    invertTree(root.left);
    invertTree(root.right);
}