DEV Community

codingpineapple
codingpineapple

Posted on

1 1

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay