Created
July 15, 2015 11:34
-
-
Save oskar-j/da36c87f90554cbdd282 to your computer and use it in GitHub Desktop.
Check amplitude of a tree in Python language (recursive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(T): | |
amplitudes = [] | |
if (T[1] is None and T[2] is None): | |
return 0 | |
if (T[1] is not None): | |
walk(T[1], T[0], T[0], amplitudes) | |
if (T[2] is not None): | |
walk(T[2], T[0], T[0], amplitudes) | |
return max(amplitudes) | |
def walk(node, m, x, amplitudes): | |
""" iterate tree in pre-order depth-first search order """ | |
m = min(node[0], m) | |
x = max(node[0], x) | |
if (node[1] is not None): | |
walk(node[1], m, x, amplitudes) | |
if (node[2] is not None): | |
walk(node[2], m, x, amplitudes) | |
if (node[1] is None and node[2] is None): | |
amplitudes.append(abs(x-m)) | |
print solution( (1, None, None) ) | |
t = (5, (8, (12, None, None), (2, None, None)), | |
(9, (7, (1, None, None), None), (4, (3, None, None), None))) | |
print solution(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment