refactor: 0102.二叉树的层序遍历.md

This commit is contained in:
qiufeihong2018
2024-04-29 17:08:26 +08:00
parent d7863c9dbf
commit 4ca945f998

View File

@ -1297,26 +1297,26 @@ func averageOfLevels(root *TreeNode) []float64 {
```javascript ```javascript
var averageOfLevels = function(root) { var averageOfLevels = function(root) {
//层级平均值 let res = [],
let res = [], queue = []; queue = [];
queue.push(root); queue.push(root);
while (queue.length) {
while(queue.length && root!==null) { // 每一层节点个数;
//每一层节点个数 let lengthLevel = queue.length,
let length = queue.length; len = queue.length,
//sum记录每一层的和 // sum记录每一层的和;
let sum = 0; sum = 0;
for(let i=0; i < length; i++) { while (lengthLevel--) {
let node = queue.shift(); const node = queue.shift();
sum += node.val; sum += node.val;
node.left && queue.push(node.left); // 队列存放下一层节点
node.right && queue.push(node.right); node.left && queue.push(node.left);
} node.right && queue.push(node.right);
//每一层的平均值存入数组res
res.push(sum/length);
} }
// 求平均值
return res; res.push(sum / len);
}
return res;
}; };
``` ```
@ -1927,26 +1927,28 @@ func max(x, y int) int {
#### Javascript #### Javascript
```javascript ```javascript
var largestValues = function(root) { var largestValues = function (root) {
//使用层序遍历 let res = [],
let res = [], queue = []; queue = [];
queue.push(root); queue.push(root);
if (root === null) {
while(root !== null && queue.length) {
//设置max初始值就是队列的第一个元素
let max = queue[0].val;
let length = queue.length;
while(length--) {
let node = queue.shift();
max = max > node.val ? max : node.val;
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
//把每一层的最大值放到res数组
res.push(max);
}
return res; return res;
}
while (queue.length) {
let lengthLevel = queue.length,
// 初始值设为负无穷大
max = -Infinity;
while (lengthLevel--) {
const node = queue.shift();
// 在当前层中找到最大值
max = Math.max(max, node.val);
// 找到下一层的节点
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
res.push(max);
}
return res;
}; };
``` ```