import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return TreeNode类
     */
   public TreeNode invertTree (TreeNode root) {
        // write code here
        if(root==null||(root.left==null && root.right==null)){
            return root;
        }
        search(root);
        return root;
    }
    
    public void search(TreeNode root){
        if(root==null){
            return;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.right = left;
        root.left = right;
        search(left);
        search(right);
    }
}

本题考察的知识点主要是左右子树的对换,所用编程语言为java.

我们主需要从上到下每次将结点的左右子树进行对换,从下到下依次进行对换就能得到题目要求的二叉树。