Recursive Data Structure in JavaScript
Level 5276 keystrokes
Uses recursion to traverse and sum all values in a tree structure.
JavaScript code
// Define a tree structure with nested children1const tree = { // Root node with value 12 value: 1, // Array of child nodes3 children: [ // First child: value 2, no children4 { value: 2, children: [] }, // Second child: value 3, has one child5 { value: 3, children: [ // Grandchild: value 46 { value: 4, children: [] }7 ]}8 ]9};10 // Recursive function to sum all values11function sumTree(node) { // Start with the current node's value12 let sum = node.value; // Iterate through all children13 for (const child of node.children) { // Recursively add child's sum to total14 sum += sumTree(child);15 } // Return the accumulated sum16 return sum;17}18 // Output: 1 + 2 + 3 + 4 = 1019console.log(sumTree(tree));Output
10
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
:× 8{× 6}× 6,× 5;× 5(× 5)× 5[× 4]× 4.× 3