Skip to content

Evaluate N-ary Expression Tree

01 · Question

Evaluate an N-ary tree where internal nodes are operations (sum, product, min, max) and leaves are numbers.

02 · Solution

Reference solution

1def evaluate(root: 'NNode') -> int:
2 if root.kind == 'num':
3 return root.num
4 vals = [evaluate(child) for child in root.children]
5 if root.kind == 'sum':
6 return sum(vals)
7 if root.kind == 'product':
8 res = 1
9 for v in vals:
10 res *= v
11 return res
12 if root.kind == 'max':
13 return max(vals)
14 return min(vals)