二叉树层序遍历

188 阅读2分钟

「这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战

题目

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

 

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回:

[3,9,20,15,7]

提示:

  1. 节点总数 <= 1000

题目分析

这个题目就是考察二叉树的广度优先遍历BFS,Breadth First Search,可以使用队列来解决这个问题。

代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>(){{
            add(root);
        }};
        ArrayList<Integer> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            result.add(treeNode.val);
            if (treeNode.left != null) {
                queue.add(treeNode.left);
            }
            if (treeNode.right!=null) {
                queue.add(treeNode.right);
            }
        }
        int[] res = new int[result.size()];
        for (int i=0;i<result.size();i++) {
            res[i] = result.get(i);
        }
        return res;
    }
}

这是我用java实现的功能,每个题都用不同的解法和写法,我大体整理了一下自己的思路然后就写了,也没有再想其他的方法,如果你有更好的解法,欢迎和我留言,我们一起进步,一起学习数据结构,共同进步,通过这道题能更熟悉二叉树的遍历的操作。

这是二叉树的层序遍历,就是按照树🌲的层从左到右依次遍历,除了层序遍历,还有先序遍历,后序遍历和中序遍历。

int[] res = new int[result.size()];
        for (int i=0;i<result.size();i++) {
            res[i] = result.get(i);
        }

这部分代码是将list转为数组,代码都是固定的思路,熟练掌握才能基于这些解决它的一些变种的问题。

小知识

今天的小知识给大家说一下线程池,线程池主要的作用是实现线程的复用,线程资源的管理,线程池的几个参数有线程的核心线程的数量,最大线程的数量和超过线程的时候的存活时间,还有任务队列,主要保存提交了但没有执行的任务,线程工厂和失败策略。

总结

这篇文章主要解决了二叉树的层序遍历

如果有不当之处,欢迎指正。