mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
refactor: 0102.二叉树的层序遍历.md
This commit is contained in:
@ -1297,25 +1297,25 @@ 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.left && queue.push(node.left);
|
||||||
node.right && queue.push(node.right);
|
node.right && queue.push(node.right);
|
||||||
}
|
}
|
||||||
//每一层的平均值存入数组res
|
// 求平均值
|
||||||
res.push(sum/length);
|
res.push(sum / len);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
@ -1928,24 +1928,26 @@ func max(x, y int) int {
|
|||||||
|
|
||||||
```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) {
|
return res;
|
||||||
//设置max初始值就是队列的第一个元素
|
}
|
||||||
let max = queue[0].val;
|
while (queue.length) {
|
||||||
let length = queue.length;
|
let lengthLevel = queue.length,
|
||||||
while(length--) {
|
// 初始值设为负无穷大
|
||||||
let node = queue.shift();
|
max = -Infinity;
|
||||||
max = max > node.val ? max : node.val;
|
while (lengthLevel--) {
|
||||||
|
const node = queue.shift();
|
||||||
|
// 在当前层中找到最大值
|
||||||
|
max = Math.max(max, node.val);
|
||||||
|
// 找到下一层的节点
|
||||||
node.left && queue.push(node.left);
|
node.left && queue.push(node.left);
|
||||||
node.right && queue.push(node.right);
|
node.right && queue.push(node.right);
|
||||||
}
|
}
|
||||||
//把每一层的最大值放到res数组
|
|
||||||
res.push(max);
|
res.push(max);
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user