226. Invert Binary Tree

Invert a binary tree.

     4
   /   
  2     7
 /    / 
1   3 6   9
to
     4
   /   
  7     2
 /    / 
9   6 3   1
翻转二叉树,本题属于容易题题目容易理解,可以通过层次遍历方法进行反转,类似【637. Average of Levels in Binary Tree】题目,
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        
        while(!q.isEmpty())
        {
            TreeNode tmp= null;
            TreeNode t= q.poll();
            tmp = t.left;
            t.left = t.right;
            t.right = tmp;
            
            if(t.left != null) q.add(t.left);
            if(t.right != null) q.add(t.right);
        }
        return root;
    }
}
 
上面的方法浅显易懂,经验上来说,二叉树的某些规律性的操作可以使用递归方法,代码如下:
public TreeNode invertTree(TreeNode root) {
    if (root == null) {
        return null;
    }
    TreeNode right = invertTree(root.right);
    TreeNode left = invertTree(root.left);
    root.left = right;
    root.right = left;
    return root;
}
原文地址:https://www.cnblogs.com/wxshi/p/7598538.html