diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index b9943f39..0a98ab88 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1297,26 +1297,26 @@ func averageOfLevels(root *TreeNode) []float64 { ```javascript var averageOfLevels = function(root) { - //层级平均值 - let res = [], queue = []; - queue.push(root); - - while(queue.length && root!==null) { - //每一层节点个数 - let length = queue.length; - //sum记录每一层的和 - let sum = 0; - for(let i=0; i < length; i++) { - let node = queue.shift(); - sum += node.val; - node.left && queue.push(node.left); - node.right && queue.push(node.right); - } - //每一层的平均值存入数组res - res.push(sum/length); + let res = [], + queue = []; + queue.push(root); + while (queue.length) { + // 每一层节点个数; + let lengthLevel = queue.length, + len = queue.length, + // sum记录每一层的和; + sum = 0; + while (lengthLevel--) { + const node = queue.shift(); + sum += node.val; + // 队列存放下一层节点 + node.left && queue.push(node.left); + node.right && queue.push(node.right); } - - return res; + // 求平均值 + res.push(sum / len); + } + return res; }; ``` @@ -1927,26 +1927,28 @@ func max(x, y int) int { #### Javascript: ```javascript -var largestValues = function(root) { - //使用层序遍历 - let res = [], queue = []; - queue.push(root); - - 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); - } - +var largestValues = function (root) { + let res = [], + queue = []; + queue.push(root); + if (root === null) { 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; }; ```