102. Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal
Python
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
return self._travel([], 0, root)
def _travel(self, result, level, node):
if not node:
return result
if len(result) < level+1:
result.append([])
result[level].append(node.val)
self._travel(result, level+1, node.left)
self._travel(result, level+1, node.right)
return result
Javascript
var levelOrder = function(root) {
const queue = [];
const res = [];
let level = 0;
if (root) queue.push(root);
while (queue.length) {
const total = queue.length;
res.push([]);
for (let i = 0; i < total; i++) {
const currNode = queue.shift();
res[level].push(currNode.val);
if (currNode.left) queue.push(currNode.left);
if (currNode.right) queue.push(currNode.right);
}
level += 1;
}
return res;
};