#C7481. Calculate Total Age in a Genealogical Tree
Calculate Total Age in a Genealogical Tree
Calculate Total Age in a Genealogical Tree
You are given a genealogical tree represented in JSON format. Each node in the tree represents a person and is defined by two keys: age
(an integer) and children
(an object/dictionary with similar structures representing the person's descendants).
Your task is to compute the sum of the ages of all individuals in the tree. The input will be provided on stdin as a JSON string, and your program should output the total age on stdout.
Note: The tree can be empty or have multiple levels of nesting. Ensure that your solution correctly handles empty trees and deeply nested structures.
Example:
Input: { "John": { "age": 50, "children": { "Michael": { "age": 30, "children": { "Sarah": { "age": 10, "children": {} }, "Tom": { "age": 8, "children": {} } } }, "Anna": { "age": 28, "children": { "James": { "age": 3, "children": {} } } } } } }</p>Output: 129
inputFormat
The input consists of a single JSON string read from stdin. This JSON object represents the genealogical tree. Each key is a person's name and its value is an object with two keys:
age
: An integer representing the age of the person.children
: A JSON object representing the descendants of the person, each following the same structure.
The tree can be empty (i.e. an empty JSON object: {}
).
outputFormat
The output is a single integer printed on stdout representing the total sum of ages of all individuals in the provided genealogical tree.
## sample{
"John": {
"age": 50,
"children": {
"Michael": {
"age": 30,
"children": {
"Sarah": { "age": 10, "children": {} },
"Tom": { "age": 8, "children": {} }
}
},
"Anna": {
"age": 28,
"children": {
"James": { "age": 3, "children": {} }
}
}
}
}
}
129