二叉树的层次遍历

news2024/9/20 10:54:55

文章目录

  • 二叉树的层次遍历
    • 二叉树的层次遍历
    • 107. 二叉树的层序遍历 II
    • 199. 二叉树的右视图
    • 637.二叉树的层平均值
    • 429. N 叉树的层序遍历
    • 515.在每个树行中找最大值
    • 116. 填充每个节点的下一个右侧节点指针
    • 填充每个节点的下一个右侧节点指针II
    • 104.二叉树的最大深度
    • 二叉树的最小深度

二叉树的层次遍历

在这里插入图片描述

二叉树的层次遍历

在这里插入图片描述
bfs法:
关键点在于queue.size()

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> list1 = new ArrayList<>();
            //关键
            int len = queue.size();
            
            while(len > 0){
                TreeNode temp = queue.poll();
                list1.add(temp.val);
                if(temp.left != null) queue.add(temp.left);
                if(temp.right != null) queue.add(temp.right);
                len--;
            }
            list.add(list1);
        }
        return list;
    }
}

在这里插入图片描述
dfs:
递归方式
此方法不太熟悉

class Solution {
    List<List<Integer>> resList = new ArrayList<List<Integer>>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        dfs(root,0);
        return resList;
    }
    public void dfs(TreeNode root,int k){
        if(root == null) return;
        //每层k的数字都是固定的
        k++;
        if(resList.size() < k){
            List<Integer> item = new ArrayList<>();
            resList.add(item);
        }
        resList.get(k - 1).add(root.val);
        dfs(root.left,k);
        dfs(root.right,k);
    }
}

在这里插入图片描述

107. 二叉树的层序遍历 II

在这里插入图片描述
在上一题基础上反转结果即可Collections.reverse(),请记住这个方法。

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> list1 = new ArrayList<>();
            //关键
            int len = queue.size();
            
            while(len > 0){
                TreeNode temp = queue.poll();
                list1.add(temp.val);
                if(temp.left != null) queue.add(temp.left);
                if(temp.right != null) queue.add(temp.right);
                len--;
            }
            list.add(list1);
        }
        Collections.reverse(list);
        return list;
    }
    }

在这里插入图片描述

199. 二叉树的右视图

在这里插入图片描述
采用dfs思路

class Solution {
    List<Integer> list;
    public List<Integer> rightSideView(TreeNode root) {
        list = new ArrayList<>();
        f(root,0);
        return list;
    }
    void f(TreeNode root,int depth){
        if(root == null) return;
        depth++;
        if(list.size() < depth){
            list.add(root.val);
        }
        f(root.right,depth);
        f(root.left,depth);
    }
}

在这里插入图片描述
bfs法:

// 199.二叉树的右视图
public class N0199 {
    /**
     * 解法:队列,迭代。
     * 每次返回每层的最后一个字段即可。
     *
     * 小优化:每层右孩子先入队。代码略。
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();

        if (root == null) {
            return list;
        }

        que.offerLast(root);
        while (!que.isEmpty()) {
            int levelSize = que.size();

            for (int i = 0; i < levelSize; i++) {
                TreeNode poll = que.pollFirst();

                if (poll.left != null) {
                    que.addLast(poll.left);
                }
                if (poll.right != null) {
                    que.addLast(poll.right);
                }

                if (i == levelSize - 1) {
                    list.add(poll.val);
                }
            }
        }

        return list;
    }
}

637.二叉树的层平均值

在这里插入图片描述

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<Double> list = new ArrayList<>();
        if(root == null) return list;
        queue.add(root);
        while(!queue.isEmpty()){
            //关键
            int len = queue.size();
            int length = len;
            double res = 0.0;
            while(len > 0){
                TreeNode temp = queue.poll();
                 res += temp.val;
                if(temp.left != null) queue.add(temp.left);
                if(temp.right != null) queue.add(temp.right);
                len--;
            }
            res /= length;
            list.add(res);
        }
        return list;
    }
}

在这里插入图片描述

429. N 叉树的层序遍历

在这里插入图片描述

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        Queue<Node> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> list1 = new ArrayList<>();
            //关键
            int len = queue.size();
            
            while(len > 0){
                Node temp = queue.poll();
                list1.add(temp.val);
                //关键点
                List<Node> children = temp.children;
                for (Node child : children) {
                    if (child != null) {
                        queue.offer(child);
                    }
                }
                len--;
            }
            list.add(list1);
        }
        return list;
    }
}

在这里插入图片描述

515.在每个树行中找最大值

在这里插入图片描述

/**
 * 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 List<Integer> largestValues(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        if(root == null) return list;
        queue.add(root);
        while(!queue.isEmpty()){
            //关键
            int len = queue.size();
            int res = Integer.MIN_VALUE;
            while(len > 0){
                TreeNode temp = queue.poll();
                res = Math.max(res,temp.val);
                //关键点
                if(temp.left != null) queue.offer(temp.left);
                if(temp.right != null) queue.offer(temp.right);
                len--;
            }
            list.add(res);
            
        }
        return list;
    }
}

在这里插入图片描述

116. 填充每个节点的下一个右侧节点指针

在这里插入图片描述
本题依然是层序遍历,只不过在单层遍历的时候记录一下本层的头部节点,然后在遍历的时候让前一个节点指向本节点就可以了

class Solution {
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if(root == null) return null;
        queue.add(root);
        while(!queue.isEmpty()){
            //关键,遍历时提前拎出来头节点
            int len = queue.size();
            Node temp = queue.poll();
            //关键点,先找到每行头节点
            if(temp.left != null) queue.offer(temp.left);
            if(temp.right != null) queue.offer(temp.right);
            for(int index = 1;index < len;index++){
                Node next = queue.poll();
                if(next.left != null) queue.offer(next.left);
                if(next.right != null) queue.offer(next.right);
                temp.next = next;
                temp = next;
            }
            }
            return root;
        }
        
    

在这里插入图片描述

填充每个节点的下一个右侧节点指针II

在这里插入图片描述

104.二叉树的最大深度

在这里插入图片描述

/**
 * 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 {
    int res = 0;
    public int maxDepth(TreeNode root) {
        dfs(root,0);
        return res;
    }
    void dfs(TreeNode root,int k){
        if(root == null) return;
        k++;
        res = Math.max(k,res);
        dfs(root.left,k);
        dfs(root.right,k);
    }
}

在这里插入图片描述

二叉树的最小深度

在这里插入图片描述
需要注意的是,只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子为空则不是最低点.
dfs:

/**
 * 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 {
    int res = Integer.MAX_VALUE;
    public int minDepth(TreeNode root) {
        dfs(root,0);
        return res == Integer.MAX_VALUE?0:res;
    }
    void dfs(TreeNode root,int k){
        if(root == null) return;
        k++;
        if(root.left == null && root.right == null) res = Math.min(res,k);
        dfs(root.left,k);
        dfs(root.right,k);
        
    }

}

在这里插入图片描述
bfs:

class Solution {
    public int minDepth(TreeNode root){
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            depth++;
            TreeNode cur = null;
            for (int i = 0; i < size; i++) {
                cur = queue.poll();
                //如果当前节点的左右孩子都为空,直接返回最小深度
                if (cur.left == null && cur.right == null){
                    return depth;
                }
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
        }
        return depth;
    }

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/182881.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ESPnet

文章目录关于 ESPnet安装配置运行 yesno关于 ESPnet github&#xff1a; https://github.com/espnet/espnet ESPnet is an end-to-end speech processing toolkit covering end-to-end speech recognition, text-to-speech, speech translation, speech enhancement, speaker …

机器自动翻译古文拼音 - 十大宋词 - 声声慢 寻寻觅觅 李清照

声声慢寻寻觅觅 宋李清照 寻寻觅觅&#xff0c;冷冷清清&#xff0c;凄凄惨惨戚戚。 乍暖还寒时候&#xff0c;最难将息。 三杯两盏淡酒&#xff0c;怎敌他、晚来风急。 雁过也&#xff0c;最伤心&#xff0c;却是旧时相识。 满地黄花堆积&#xff0c;憔悴损&#xff0c;如今…

Web 应用程序——我的心理备忘单

介绍本文是“持续交付&#xff1a;HTML 到 Kubernetes”的一部分。虽然我迫不及待地想深入了解分布式系统的细节&#xff0c;但我发现自己处于一个不愉快的境地&#xff1a;我认为最好从前端开始写。那是因为网络应用程序是当今的标准。在多个云中部署的 ArgoCD-Kubernetes 集群…

商业智能BI,大数据时代的新趋势

根据IDC预测&#xff0c;2025年时中国产生的数据量预计将达48.6ZB&#xff0c;在全球中的比例为27.8%。在未来&#xff0c;数据会是构建现代社会的基本要素&#xff0c;也是社会的基本建设。这也不禁让我想起了最近新公布的《关于构建数据基础制度更好发挥数据要素作用的意见》…

高并发下如何保证接口的幂等性?

一、什么是幂等&#xff1f; 看一下维基百科怎么说的&#xff1a; 幂等性&#xff1a;多次调用方法或者接口不会改变业务状态&#xff0c;可以保证重复调用的结果和单次调用的结果一致。 二、使用幂等的场景 1、前端重复提交 用户注册&#xff0c;用户创建商品等操作&#…

使用这个工具,本地调试UI再也不用怕了

前言&#xff1a;在我们日常使用中&#xff0c;很多场景都会用到UI自动化&#xff0c;通用的都是PythonSelenium的方式。今天介绍一种&#xff0c;不用通过代码&#xff0c;直接通过页面可视化配置的方式&#xff0c;就可以完成我们想要的自动化场景。话不多说&#xff0c;正片…

ElasticSearch - 结果处理

目录 结果处理-排序 结果处理-分页 结果处理-高亮 结果处理-排序 elasticsearch默认是根据相关度算分(_score)来排序&#xff0c;但是也支持自定义方式对搜索结果排序可以排序字段类型有&#xff1a;keyword类型、数值类型、地理坐标类型、日期类型等普通字段排序keyword、数…

pytorch图像分类全流程(五)--图像分类算法精度评估指标

本次我们来学习图像分类算法精度的各种评估指标&#xff1a;precision、recall、accuracy、f1-score、AP、AUC。 首先我们来学一个很重要的概念&#xff0c;混淆矩阵&#xff1a; 1.精确率(Precision)&#xff1a; 指的是所有被判定为正类&#xff08;TPFP&#xff09;中&…

8-Arm PEG-Succinamide Acid,8-Arm PEG-SAA,八臂-聚乙二醇-丁二酸酰胺供应

英文名称&#xff1a;8-Arm PEG-SAA&#xff0c;8-Arm PEG-Succinamide Acid 中文名称&#xff1a;八臂-聚乙二醇-丁二酸酰胺 8-臂PEG-SAA是一种多臂PEG衍生物&#xff0c;在连接到一个六甘油核心的八个臂的每个末端具有羧基。PEG和丁二酰胺酸COOH基团之间存在C3酰胺键。PEG酸…

HTML中引入CSS样式的第一种方式:内联定义方式

<!-- HTML中引入CSS样式的第一种方式&#xff1a;内联定义方式 语法格式&#xff1a; <标签 style"样式名:样式值;样式名:样式值;样式名:样式值;..."></标签> --> <!DOCTYPE html> <html> <head> …

操作系统(day01)

文章目录操作系统的功能和目标1.作为系统资源的管理者&#xff08;从中间往两边看&#xff09;2.作为用户和计算机硬件之间的接口&#xff08;从下往上看&#xff09;操作系统的四大特征共享虚拟异步操作系统的发展与分类手工操作阶段批处理阶段--多道批处理系统分时操作系统实…

基于蜣螂算法的极限学习机(ELM)回归预测-附代码

基于蜣螂算法的极限学习机(ELM)回归预测 文章目录基于蜣螂算法的极限学习机(ELM)回归预测1.极限学习机原理概述2.ELM学习算法3.回归问题数据处理4.基于蜣螂算法优化的ELM5.测试结果6.参考文献7.Matlab代码摘要&#xff1a;本文利用蜣螂算法对极限学习机进行优化&#xff0c;并用…

QT入门与基础控件

目录 一、QT入门 1.1QT简介 1.2经典应用 1.3工程搭建 1.3.1按钮 1.3.2行编辑框 1.3.3简单确定位置 1.4信号与槽机制 二、布局管理器 2.1布局管理器 2.2输出控件 2.3输入控件 2.4按钮 2.5容器 2.5.1Group Box 2.5.2Ccroll Area 2.5.3Tool Box 2.5.4 Tab Wid…

射频脉冲频谱及退敏效应简述

当使用频谱仪测试射频脉冲信号的频谱时&#xff0c;设置不同的RBW可以得到不同的结果&#xff0c;有连续的包络谱和离散的线状谱之分。针对简单的射频脉冲而言&#xff0c;脉冲退敏效应是指&#xff0c;当显示线状谱时&#xff0c;中心载波的幅度将低于脉内平均功率&#xff0c…

网络工程师必修课主流两种方式实现不同VLAN间通信

我们知道默认不同VLAN间数据时不能通信的,想要实现不同VLAN间通信常用的有两种方式: 一、通过三层交换路由功能实现不同VLAN之间的通信 二、通过单臂路由实现不同VLAN之间的通信 1.通过三层SVI虚接口配置路由实现通信: 交换机A的配置 vlan batch 20 30 //创建VLAN20 V…

数据库概念及运算符介绍

文章目录一、介绍概念分类相关术语启动与关闭服务卸载MySQL的管理工具Navicat的下载和安装逻辑结构二、SQL介绍分类语法注释DDLDQL基本查询运算符伪表算术运算符比较运算符等号运算符安全等与运算符不等于运算符空运算符非空运算符最小值最大值运算符BETWEEN AND运算符IN运算符…

操作符详解

文章目录 算术操作符移位操作符 位操作符 赋值操作符 单目操作符 关系操作符 逻辑操作符 条件操作符 逗号表达式 下标引用、函数调用和结构成员表达式求值前言 一、算术操作符 - * / % 注意&#xff1a; 1. 除了 % 操作符之外&#xff0c;…

茕茕白兔十二年

白兔子黑兔子 一年一月&#xff1a;孤独 黑兔子主人公孤单一人躺在斐波那契试验田&#xff0c;犹如上帝造出的亚当。ta决定邀请别的兔子跟ta一起抵抗生活中的百无聊赖&#xff0c;就写下了“征友”明信片&#xff0c;并在明信片上畅想了他们在一起美好的“兔生”。 那一年的秋…

29. 两数相除

打卡!!!每日一题 今天给大家带来一道位运算类型的题目 题目描述&#xff1a; 题目示例&#xff1a; 对于这种类型的题目&#xff0c;当题目要求不能使用乘法、除法时&#xff0c;那么则需要我们从移位、或、与、异或等位运算的角度来进行考虑&#xff0c;接下来我带着大家…

Linux 软件安装 YUM管理工具 简单引入

概念引入 &#xff1a;# 首先提出一个问题&#xff0c;我们在 Linux 操作系统中是如何 安装软件的 &#xff1f;&#xff1f;>>>在 Linux 系统中&#xff0c;安装软件是有三种方式>>>第一种 &#xff1a; RPM 管理工具 第二种 &#xff1a; YUM 管理工具第三…