102. Binary tree level order traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

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],

 3

/
9 20 /
15 7

return its level order traversal as:

[ [3], [9,20], [15,7] ]


  • code
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> level = new LinkedList<>();
        if (root != null) level.offer(root);
        while (!level.isEmpty()){
            res.add(level.stream().map(n -> n.val).collect(Collectors.toList()));
            int levelSize = level.size();
            for (int i = 0; i < levelSize; i++){
                TreeNode cur = level.pollFirst();
                if (cur.left != null) level.offerLast(cur.left);
                if (cur.right != null) level.offerLast(cur.right);
            }
        }
        return res;
    }
}
  • code
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return None
        res = []
        level = [root]
        while level:
            res.append([node.val for node in level])
            level = [i for node in level for i in (node.left, node.right) if i]
        return res
        
  • c0
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        
        def traversal(root, level, res):
            if not root:
                return
            if len(res) <= level:
                res.append([])
            res[level].append(root.val)
            traversal(root.left, level+1, res)
            traversal(root.right, level+1, res)
            
        res = [[]]
        traversal(root,0,res)
        return res