class Tree(object):
def __init__(self, x, left=None, right=None):
self.value = x
self.left = left
self.right = right
x = Tree(1, Tree(0, Tree(1), Tree(3)), Tree(4))
def solution(t):
if not t:
return 0
stack = [(t, 0)]
branchesSum = 0
while stack:
node, v = stack.pop()
if node.left or node.right:
#depth first search
# the v is a little confusing to understand but easier to see in python tutor
# it goes from 1 to 10 to 100 etc. based on the height of the branch
# can probably do something like str() and converting back to int() as well
if node.left:
stack.append((node.left, node.value + v * 10))
if node.right:
stack.append((node.right, node.value + v * 10))
else:
branchesSum += node.value + v * 10
return branchesSum
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter