226. 翻转二叉树

导读:本篇文章讲解 226. 翻转二叉树,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

226. 翻转二叉树icon-default.png?t=M666https://leetcode.cn/problems/invert-binary-tree/
难度简单1361

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:

226. 翻转二叉树

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

226. 翻转二叉树

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

提示:

  • 树中节点数目范围在 [0, 100] 内
  • -100 <= Node.val <= 100

通过次数501,076提交次数631,866

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {

        //递归翻转

        if(root==null) return root;
        TreeNode node= root.right;
        root.right = root.left;
        root.left = node;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
         //广度优先遍历 + 右->左
        
        if(root==null) return root;

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty())
        {
            int size = queue.size();
            while(size>0)
            {
                TreeNode node = queue.poll();
                TreeNode temp = node.right;
                node.right = node.left;
                node.left = temp;
                if(node.right!=null) queue.offer(node.right);
                if(node.left!=null) queue.offer(node.left);
                size--;
            }
        }
        return root;

    }
}

226. 翻转二叉树

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69016.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!