Created
September 3, 2022 00:08
-
-
Save germanescobar/ec350dd9277ade874302517b6c59f383 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var averageOfLevels = function(root) { | |
const valuesByLevel = [] | |
dfs(root, 0, valuesByLevel) | |
const result = [] | |
for (let i=0; i < valuesByLevel.length; i++) { | |
const arr = valuesByLevel[i] | |
result.push(average(arr)) | |
} | |
return result | |
}; | |
function average(arr) { | |
let sum = 0 | |
for (let j=0; j < arr.length; j++) { | |
sum += arr[j] | |
} | |
return sum / arr.length | |
} | |
function dfs(node, level, valuesByLevel) { | |
if (!node) return | |
if (valuesByLevel[level]) { | |
const arr = valuesByLevel[level] | |
arr.push(node.val) | |
} else { | |
valuesByLevel[level] = [node.val] | |
} | |
dfs(node.left, level + 1, valuesByLevel) | |
dfs(node.right, level + 1, valuesByLevel) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/problems/average-of-levels-in-binary-tree/