Is there a way to calculate the max difference between node values without storing in a list? I was hoping to do it in 1 pass, but it doesn't seem possible. This was from a codility interview question to calculate the amplitude of the binary tree defined as the max absolute difference of the nodes.
def max_diff(nodes):
return abs(max(nodes) - min(nodes))
def amplitude(T):
nodes = []
def calc_amplitude(T, nodes):
if not isinstance(T, tuple):
if not isinstance(T, int):
return 0
nodes.append(T)
return T
else:
[calc_amplitude(t, nodes) for t in T]
return max_diff(nodes)
return calc_amplitude(T, nodes)
tree = (5, (8, (12, None, None), (2, None, None)),(9, (7, (1, None, None), None), (4, (3, None, None), None)))
print amplitude(tree)