您需要在二叉树的每一行中找到最大的值。
递归【BFS & DFS】
/**
* 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) {
const res = []
const largest = (root, level) =>{
if (!root) return
if (level >= res.length) res[level] = Number.MIN_SAFE_INTEGER;
res[level] = Math.max(res[level], root.val);
root.left && largest(root.left, level + 1);
root.right && largest(root.right, level + 1)
}
largest(root, 0)
return res
};
var largestValues = function (root) {
const res = [], stack = [];
if (!root) return res;
stack.push(root);
while (stack.length) {
let temp = Number.MIN_SAFE_INTEGER,
len = stack.length;
for (let i = 0; i < len; i++) {
const node = stack.shift();
temp = Math.max(temp, node.val);
node.left && stack.push(node.left);
node.right && stack.push(node.right);
}
res.push(temp);
}
return res;
};