Invert Binary Tree

Question:

Invert a binary tree.

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

Lesson Learned:

  • you must make sure the node is not null to reuse it!

          if (root.left != null) {
              invertBinaryTree(root.left);
          }
          if (root.right != null) {
              invertBinaryTree(root.right);
          }
    

Recursion:

/**
 * 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
     */
    private TreeNode temp = null;

    public void invertBinaryTree(TreeNode root) {
        // write your code here
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            return;
        }
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        // you must make sure the node is not null to reuse it!
        if (root.left != null) {
            invertBinaryTree(root.left);
        }
        if (root.right != null) {
            invertBinaryTree(root.right);
        }
    }
}