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 children
1const tree = {
// Root node with value 1
2 value: 1,
// Array of child nodes
3 children: [
// First child: value 2, no children
4 { value: 2, children: [] },
// Second child: value 3, has one child
5 { value: 3, children: [
// Grandchild: value 4
6 { value: 4, children: [] }
7 ]}
8 ]
9};
10
// Recursive function to sum all values
11function sumTree(node) {
// Start with the current node's value
12 let sum = node.value;
// Iterate through all children
13 for (const child of node.children) {
// Recursively add child's sum to total
14 sum += sumTree(child);
15 }
// Return the accumulated sum
16 return sum;
17}
18
// Output: 1 + 2 + 3 + 4 = 10
19console.log(sumTree(tree));

Output

10
Practice typing this code

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

More JavaScript examples at level 5

← JavaScript typing practice