Thursday, February 11, 2016

Invert Binary Tree

Invert Binary Tree

Invert a binary tree.

Example
  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

Challenge
Do it in recursion is acceptable, can you do it without recursion?


Traverse the tree. For each node, switch his left child and right child.


 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
27
28
29
30
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        // write your code here
        if (root == null) {
            return;
        }
        
        TreeNode tmp = root.right;
        root.right = root.left;
        root.left = tmp;
        
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
    }
}