DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 515. Find Largest Value in Each Tree Row (javascript solution)

Description:

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Solution:

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

// Bfs
var largestValues = function(root) {
    if(!root) return []
    const output = []
    let queue = []
    queue.push(root)
    while(queue.length) {
        const len = queue.length
        // Keep track of the max per level
        let max = -Infinity
        for(let i = 0; i < len; i++){
            const cur = queue.shift()
            max = Math.max(max, cur.val)
            if(cur.left) queue.push(cur.left)
            if(cur.right) queue.push(cur.right)
        }
        // Add the max to the output array
        output.push(max)
    }
    return output
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)