照例要考虑树为空的情况。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if(root===null){
return root;
}
if(root.left!==null||root.right!==null){
var temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left!==null){
invertTree(root.left);
}
if(root.right!==null){
invertTree(root.right);
}
}
return root;
};