102. Binary Tree Level Order Traversal

lpy1990
Given a binary tree, return the level order traversal of its nodes'
values. (ie, from left to right, level by level).

For example: Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as: [ [3], [9,20], [15,7] ]

思路

用宽度优先搜索的方法, 用while循环遍历树的每一层, for循环做每一层内的遍历

复杂度

时间 O(n) 空间O(n)

代码

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i =0; i< size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}
阅读 1.2k

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏