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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more