Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1

Code

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

Note

  • 容易犯的错误:注意要把left 和 right先存一下,不能直接pass。