【BFS】LeetCode 102. 二叉树的层序遍历

题目链接

102. 二叉树的层序遍历

思路

树的层次遍历模板题,需要使用一个变量来记录每一层的结点个数

代码

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null){
            return new ArrayList<List<Integer>>();
        }
        
        Queue<TreeNode> queue = new ConcurrentLinkedDeque<>();
        List<List<Integer>> result = new ArrayList<>();

        queue.add(root);
        while(!queue.isEmpty()){
            int currentCnt = queue.size();
            List<Integer> temp = new ArrayList<>();

            for(int i = 0; i < currentCnt; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
                temp.add(node.val);
            }
            result.add(temp);
        }

        return result;
    }
}
posted @ 2023-01-11 15:15  Frodo1124  阅读(37)  评论(0编辑  收藏  举报