Skip to main content

515.js

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var largestValues = function (root) {
if (!root) return []

const result = []
const queue = [root]

while (queue.length > 0) {
const n = queue.length
let max = -Infinity

for (let i = 0; i < n; i++) {
const node = queue.shift()
// max = Math.max(max, node.val)
if (node.val > max) {
max = node.val
}

if (node.left) queue.push(node.left)
if (node.right) queue.push(node.right)
}
result.push(max)
}

return result
}