Middle+
Task: traverse a tree of objects (each object has fields value and elements) and calculate the sum of all values. How would you implement this?
sobes.tech AI
Answer from AI
To traverse a tree of objects with fields value and elements (where elements is an array of child objects) and calculate the sum of all values, you can use a recursive function.
Example in JavaScript:
function sumValues(node) {
let sum = node.value;
if (node.elements && node.elements.length > 0) {
for (const child of node.elements) {
sum += sumValues(child);
}
}
return sum;
}
// Example usage:
const tree = {
value: 10,
elements: [
{ value: 5, elements: [] },
{ value: 3, elements: [
{ value: 2, elements: [] }
]}
]
};
console.log(sumValues(tree)); // 20
The sumValues function takes a node, adds its value to the sum, then recursively calls itself for all child elements, accumulating the total sum.