DEV Community


Posted on


102. Binary Tree Level Order Traversal (javascript solution)


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


Time Complexity : O(n)
Space Complexity: O(n)

// BFS
var levelOrder = function(root) {
    if(!root) return []
    const queue = []
    const output = []
    while(queue.length) {
        // Remove all the current nodes in the queue and add each node's children to the queue
        const len = queue.length
        const row = []
        for(let i = 0; i < len; i++) {
            const cur = queue.shift()
            if(cur.left) queue.push(cur.left)
            if(cur.right) queue.push(cur.right)
            // Push the current node val to the row array
        // Push the current row array into the output array
    return output
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!