难度: 中等
题目
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例 1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/ \
3 2
/ \ \
5 3 9
示例 2:
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/ \
2 3
示例 3:
输入: root = [1]
输出: [1]
示例 4:
输入: root = [1,null,2]
输出: [1,2]
解释:
1
\
2
示例 5:
输入: root = []
输出: []
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
思路
BFS (广度优先遍历)
- 处理根节点的特殊情况
- 记录每个节点的左右子节点, 加入 next 数组, 用于递归判断
题解
/**
* 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 []
// 先处理根节点
res.push(root.val)
// 每层最大值数组
let res = []
const maxVal = (...tn) => {
if (tn.length === 0) return
// 当前层的最大值
let maxTemp = -Infinity
// 用于存在下一层需要判断的节点
let next = []
for (let i = 0; i < tn.length; i++) {
if (tn[i] === null) continue
if (tn[i].val > maxTemp) {
maxTemp = tn[i].val
}
if (tn[i].left) next.push(tn[i].left)
if (tn[i].right) next.push(tn[i].right)
}
if (maxTemp > -Infinity) res.push(maxTemp)
maxVal(...next)
}
maxVal(root.left, root.right)
return res
};
// test
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
let rootTree = new TreeNode(
1,
new TreeNode(3, new TreeNode(5, null, null), new TreeNode(3, null, null)),
new TreeNode(2, new TreeNode(null, null, null), new TreeNode(9, null, null))
)
console.log('largestValues', largestValues(rootTree))
结果
执行用时:72 ms, 在所有 JavaScript 提交中击败了94.32%的用户
内存消耗:43.3 MB, 在所有 JavaScript 提交中击败了12.50%的用户
通过测试用例:78 / 78