二叉树的层序遍历&力扣对应题 Java

二叉树的层序遍历 Java

  • [102. 二叉树的层序遍历](#102. 二叉树的层序遍历)
    • [错误① 队列的声明](#错误① 队列的声明)
    • [错误② `List<List<Integer>>`的声明](#错误② List<List<Integer>>的声明)
  • [107. 二叉树的层序遍历 II](#107. 二叉树的层序遍历 II)
  • [199. 二叉树的右视图](#199. 二叉树的右视图)
  • 637.二叉树的层平均值
  • 429.N叉树的层序遍历
    • [注意① LeetCode中N叉树节点的定义](#注意① LeetCode中N叉树节点的定义)
    • [注意② 增强for的使用](#注意② 增强for的使用)
  • [515. 在每个树行中找最大值](#515. 在每个树行中找最大值)
    • [错误① 最值中初始值的问题](#错误① 最值中初始值的问题)
    • [错误② Math库函数 max() 、min()](#错误② Math库函数 max() 、min())

跟着代码随想录学到了二叉树层序遍历,对相关的题进行解答&总结。

102. 二叉树的层序遍历

二叉树的层序遍历是借助队列 Queue实现的。
代码注意点 ① for循环是为了保证弹出每一行不多不少的节点,
②每一行的大小通过上一步骤的队列size确定,但是要通过另一个变量保存起来,因为队列的大小是会动态变化的

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();//又错了
        if(root == null) return ans;

        Queue<TreeNode> q = new LinkedList<TreeNode>(); //又错了
        q.offer(root);
        int size = 0;
        while(!q.isEmpty()) {
            size = q.size();

            List<Integer> qq = new ArrayList<>();
            for(int i = 0; i < size; i++) { 
                //这里不可以用q.size(),因为poll之后是会变的
                TreeNode tmp = q.poll();
                qq.add(tmp.val);添加的是值,不是节点
                if(tmp.left != null) q.offer(tmp.left);
                if(tmp.right != null) q.offer(tmp.right);
            }
            ans.add(qq);
        }

        return ans;
    }
}

错误① 队列的声明

java 复制代码
 Queue<TreeNode> q = new LinkedList<TreeNode>(); 

错误② List<List<Integer>>的声明

java 复制代码
List<List<Integer>> ans = new ArrayList<List<Integer>>();

107. 二叉树的层序遍历 II

思想就是,converse 普通的层序遍历的结果

java 复制代码
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        if(root == null) return ans;

        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int size = 1;
        while(!que.isEmpty()) {
            size = que.size();
            List<Integer> item = new ArrayList<>();

            for(int i = 0; i < size; i++) {
                TreeNode tmp = que.poll(); // poll & pop
                item.add(tmp.val);
                if(tmp.left != null) que.offer(tmp.left);
                if(tmp.right != null) que.offer(tmp.right);
            }

            ans.add(item);
        }

        Collections.reverse(ans);
        return ans;
    }
}

199. 二叉树的右视图

java 复制代码
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root == null) return ans;

        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int size = 1;
        while(!que.isEmpty()) {
            size = que.size();

            for(int i = 0; i < size; i++) {
                TreeNode tmp = que.poll(); // poll & pop
                if(i == size-1) {
                    ans.add(tmp.val);
                }
                if(tmp.left != null) que.offer(tmp.left);
                if(tmp.right != null) que.offer(tmp.right);
            }
        }

        return ans;
    }
}

637.二叉树的层平均值

java 复制代码
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ans = new ArrayList<>();
        if(root == null) return ans;

        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int size = 1;

        while(!que.isEmpty()) {
            size = que.size();
            double sum = 0.0;
            
            for(int i = 0; i < size; i++) {
                TreeNode tmp = que.poll(); // poll & pop
                sum += tmp.val;
                if(tmp.left != null) que.offer(tmp.left);
                if(tmp.right != null) que.offer(tmp.right);
            }
            sum /= size;
            ans.add(sum);
        }
        return ans;
    }
}

429.N叉树的层序遍历

java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        if(root == null) return ans;

        Queue<Node> q = new LinkedList<>();
        q.offer(root);
        int size = 0;

        while(!q.isEmpty()) {
            size = q.size();

            List<Integer> item = new ArrayList<>();
            for(int i = 0; i < size; i++) { 
                //这里不可以用q.size(),因为poll之后是会变的
                Node tmp = q.poll();
                item.add(tmp.val);添加的是值,不是节点

                for(Node n : tmp.children) {
                    if(n != null) {
                        q.offer(n);
                    }
                }
            }
            ans.add(item);
        }

        return ans;
    }
}

注意① LeetCode中N叉树节点的定义

java 复制代码
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};

注意② 增强for的使用

二叉树中,访问某节点a的左孩子 右孩子的方法是,a.left 和 a.right。

在N叉树中,可以利用增强for

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

java 复制代码
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root == null) return ans;

        Queue<TreeNode> q = new LinkedList<TreeNode>(); 
        q.offer(root);
        int size = 0;
        while(!q.isEmpty()) {
            size = q.size();

            int max = Integer.MIN_VALUE;//错了
            for(int i = 0; i < size; i++) { 
                TreeNode tmp = q.poll();
                if(tmp.val > max) max = tmp.val;
                
                if(tmp.left != null) q.offer(tmp.left);
                if(tmp.right != null) q.offer(tmp.right);
            }
            ans.add(max);
        }

        return ans;
    }
}

错误① 最值中初始值的问题

初始值设置成Integer中的 MIN_VALUE或者MAX_VALUE,不可以是0。

java 复制代码
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;

错误② Math库函数 max() 、min()

java 复制代码
 max = Math.max(max, node.val);
相关推荐
程序员清风7 分钟前
推荐几个我常听的AI播客!
java·后端·面试
唐青枫27 分钟前
Java Gradle 实战指南:从 Wrapper、Kotlin DSL 到 Spring Boot 多模块构建
java·kotlin·gradle
wuqingshun31415929 分钟前
如何理解Spring Boot中的starter?
java·spring boot·后端
带刺的坐椅30 分钟前
Solon TeamAgent 协作协议:从 SEQUENTIAL 流水线到 HIERARCHICAL 主管团队
java·ai·llm·agent·solon
wuqingshun31415938 分钟前
SpringBoot是如何实现自动配置的
java·spring boot·后端
用户0537040314341 分钟前
我的学习记录泛型
java
zhouhui00143 分钟前
AI帮我写了个Spring Boot校验,线上漏掉了这组边界条件
java·spring boot·redis·ai编程
JRedisX1 小时前
Java从零手写企业级内存数据库
java
萧瑟余晖1 小时前
JDK 20 新特性详解
java·开发语言
hdsoft_huge1 小时前
SpringBoot系列17:日志体系Logback配置,日志分割、脱敏、异常堆栈收集规范(生产级落地)
java·spring boot·logback