返回
LeetCode 题解:515. 在每个树行中找最大值,BFS,JavaScript,详细注释
前端
2023-09-24 17:22:57
## 题目
给定一棵二叉树,你需要在每一行中找到最大的值。
## 输入
* 二叉树的根节点 `root`
## 输出
* 一个数组,其中包含每一行中的最大值。
## 样例
**输入:**
1
/ \
2 3
/ \ \
4 5 6
**输出:**
[1, 3, 6]
**解释:**
第一行中的最大值为 1,第二行中的最大值为 3,第三行中的最大值为 6。
## 思路
我们可以使用广度优先搜索 (BFS) 算法来解决这个问题。BFS 算法是一种逐层遍历二叉树的算法,我们可以使用队列来存储每一层的节点。每次循环时,我们将队列中当前层的节点依次取出,并找出当前层的最大值。然后,我们将当前层每个节点的子节点依次存入队列尾部,等待下一次遍历处理。不断重复步骤 3、4,直到队列为空,即可得到每一层中的最大值。
## 代码实现
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Given a binary tree, find the maximum value in each level of the tree.
*
* @param {TreeNode} root The root node of the binary tree.
* @return {number[]} An array of the maximum values in each level of the tree.
*/
const largestValues = (root) => {
if (root === null) {
return [];
}
const queue = [root];
const result = [];
while (queue.length > 0) {
const levelSize = queue.length;
let maxValue = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
maxValue = Math.max(maxValue, node.val);
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
result.push(maxValue);
}
return result;
};
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树中的节点数。
- 空间复杂度:O(n),其中 n 是二叉树中的节点数。
总结
这道题可以使用 BFS 算法来解决,逐层遍历二叉树,找出每一层的最大值。代码实现也很简单,易于理解和学习。