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.
return abs(max(nodes) - min(nodes))
nodes = 
def calc_amplitude(T, nodes):
if not isinstance(T, tuple):
if not isinstance(T, int):
[calc_amplitude(t, nodes) for t in T]
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)))
In case that you want to know the maximum difference between two nodes on any path from root to leaf you can use following code:
def amplitude(tree, cur_min=None, cur_max=None): if tree is None: if cur_min is None: return 0 else: return cur_max - cur_min if cur_min is None: cur_min = cur_max = tree else: cur_min = min(cur_min, tree) cur_max = max(cur_max, tree) return max(amplitude(tree, cur_min, cur_max), amplitude(tree, cur_min, cur_max))
It will track minimum and maximum value on each path. Once it reaches the leaf it will simply return the difference between those two thus stopping the recursion. For non-leaf nodes it will first update minimum and maximum value. Then it recurses to both children and returns the maximum value between the two results.