栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeeTCode226. 翻转二叉树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeeTCode226. 翻转二叉树

题目描述

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

涉及tag

二叉树

算法思路

递归:
1 输入值和返回值:
传入的是根节点,返回根节点
public TreeNode invert(TreeNode root)
2 递归结束条件:
父节点成功反转,父节点的左子树和右子树也成功反转
TreeNode keeper = root.left;
root.left = root.right;
root.right = keeper;
root = root.left;
3 每层递归逻辑

层序遍历:在while循环里加入左右子树交换即可。

示例代码1
//递归遍历
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode keeper = root.right;
		root.right = root.left;
		root.left = keeper;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
示例代码2
//递归遍历
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        Deque queue = new ArrayDeque<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int n = queue.size();
            //tmp暂时存放从队列中获取的第一个树节点
            TreeNode tmp = queue.poll();
            //节点left暂时存放当前根节点的左子树
            //进行交换
            TreeNode left = tmp.left;
            tmp.left = tmp.right;
            tmp.right = left;
            if (tmp.left != null) queue.add(tmp.left);
            if (tmp.right != null) queue.add(tmp.right);
        }
        return root;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780283.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号