226. Invert Binary Tree

Posted Wanna_Go

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于226. Invert Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

226. Invert Binary Tree

letecode [226] - Invert Binary Tree

226. Invert Binary Tree

leetcode 226 Invert Binary Tree

226. Invert Binary Tree

#Leetcode# 226. Invert Binary Tree