力扣102、二叉树的层序遍历

题目:

思路:将第一层节点加入队列,并记录第一层节点个数size,一个一个弹出节点,弹出size个,每弹出一个都将弹出节点的左右孩子加入队列中。

复制代码
/**
 * 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<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList();
        Queue<TreeNode> queue = new LinkedList();
        if( root == null) return res;
        queue.add(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList();
            while(size-- > 0){
                TreeNode cur =  queue.peek();
                queue.poll();
                list.add(cur.val);
                if(cur.left != null){
                    queue.add(cur.left);
                }
                if(cur.right != null){
                    queue.add(cur.right);
                }
            }
            res.add(list);
        }

        return res;
    }
}
相关推荐
Tisfy2 小时前
LeetCode 2976.转换字符串的最小成本 I:floyd算法(全源最短路)
算法·leetcode··floyd·题解
元亓亓亓2 小时前
考研408--数据结构--day5--栈与队列的应用
数据结构·考研··408·队列
v_for_van2 小时前
力扣刷题记录4(无算法背景,纯C语言)
c语言·算法·leetcode
小高Baby@2 小时前
Golang中面向对象的三大特性之多态的理解
数据结构·golang
dazzle2 小时前
Python数据结构(十五):归并排序详解
数据结构·python·算法
.ZGR.2 小时前
认识数据结构:图——无人机防空平台的“衍生品”
java·开发语言·数据结构
2301_764441332 小时前
基于paCy模型与jsoncrack进行依存句法分析
python·算法·自然语言处理
晚风吹长发2 小时前
初步了解Linux中的线程同步问题及线程安全和死锁与生产消费者模型
linux·运维·服务器·开发语言·数据结构·安全