from collections import defaultdict
class Tree(defaultdict):
def __init__(self):
super().__init__(Tree)
t = Tree()
t['a']['b']['c'] = 10
t['a']['b']['d'] = 20
t['a']['e'] = 5
def count_leaves(d):
total = 0
for v in d.values():
if isinstance(v, dict):
total += count_leaves(v)
else:
total += v
return total
print(count_leaves(t))
#Python