[leetcode]226.Invert Binary Tree

Posted shinjia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]226.Invert Binary Tree相关的知识,希望对你有一定的参考价值。

题目

Invert a binary tree.
比如原来的树为 0 1 2
逆转后的树为 0 2 1
也就是把所有结点的左右结点互换

解法一

思路

递归

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return root;
        TreeNode tmp = invertTree(root.right);
        root.right = invertTree(root.left);
        root.left = tmp;
        return root;
    }
}

解法二

思路

非递归,用树的层次遍历

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return root;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            TreeNode left = tmp.left;
            tmp.left = tmp.right;
            tmp.right = left;
            
            if(tmp.left != null) queue.offer(tmp.left);
            if(tmp.right != null) queue.offer(tmp.right);
        }
        return root;
    }
}



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

leetcode 226 Invert Binary Tree

#Leetcode# 226. Invert Binary Tree

LeetCode 226. Invert Binary Tree

LeetCode226:Invert Binary Tree

Python解Leetcode: 226. Invert Binary Tree

Leetcode 226: Invert Binary Tree