Published
Edited
Dec 8, 2018
Insert cell
Insert cell
function* getData () {
yield* input.split(" ").map(Number);
}
Insert cell
Insert cell
function makeTree (data) {
function recur () {
let tree = {};
tree["metadata"] = [];
tree["children"] = [];

const numC = data.next().value;
const numM = data.next().value;
for (let i = 0; i < numC; i++) {
tree["children"].push(recur());
}
for (let i = 0; i < numM; i++) {
tree["metadata"].push(data.next().value);
}

return tree;
}
return recur();
}
Insert cell
tree = makeTree(getData())
Insert cell
function addMetadata (subtree) {
let sum = 0;

for (const m of subtree["metadata"]) {
sum += m;
}

for (const c of subtree["children"]) {
sum += addMetadata(c);
}
return sum;
}
Insert cell
metadataEntrySum = addMetadata(tree)
Insert cell
Insert cell
function getRootValue (subtree) {
if (!subtree) return 0;

let sum = 0;
for (const m of subtree["metadata"]) {
if (subtree["children"].length === 0) {
sum += m;
} else {
sum += getRootValue(subtree["children"][m-1]);
}
}
return sum;
}
Insert cell
rootValue = getRootValue(tree)
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more