Thinking
Use queue:
- Initialization of the root, push into the queue q
- Circular queues q, when one is not empty, to take the first element (q.shift), referred to as r
- If r.left is not empty, the r.left advance q, if r.right is not empty, the r.right advance q
Record level:
4. 0 = initial setting I;
5. The enqueued when enqueuing an object {r: root, i}
6. dequeued using es6 deconstruction assignment taken {r, i}
- To achieve the following:
var averageOfLevels = function (root) {
let q = []; // 队列
let i = 0; // 记录层次用的标记
q.push({r: root, i}); // 将根放入队列中
while(q.length > 0) { // 队列不为空
let { r, i } = q.shift(); // 得到根和层次信息
if(r) { // 根不为空
i++; // 层次加1
if(r.left) { // 左孩子不为空
q.push(r.left);
}
if(r.right) {
.push(r.right);
}
console.log(r.val, i);
}
}
}
- The above has been achieved basically traverse the level
- The following returns a new array, the subject needs to achieve
- Now it has the value of each layer and the layer number.
- The next layer of each layer and the number of key values into a map structure.
var averageOfLevels = function (root) {
let q = [];
let i = 0;
let map = new Map;
q.push({ r: root, i });
while (q.length > 0) {
let { r, i } = q.shift();
if (r) {
i++;
if (r.left) {
q.push({ r: r.left, i });
}
if (r.right) {
q.push({ r: r.right, i });
}
// 改动部分, 使用map结构存储层次的 键值对
if(map.has(i)){
let arr = map.get(i);
arr.push(r.val);
map.set(i, arr);
} else{
map.set(i,[r.val]);
}
}
}
for(let [i, key] of map){
console.log(i, key);
}
};
- Above the completion of each layer and the number of key values into a map structure.
- Modify the end of the following
for(let [i, key] of map)
internal, to meet the needs of the subject
let retArr = [];
for (let [i, key] of map) {
let sum = 0;
if (key.length > 1) {
for (let i = 0; i < key.length; i++) {
sum += key[i];
}
} else {
sum = key[0];
}
retArr[i - 1] = sum / key.length;
}
return retArr