Skip to content

Instantly share code, notes, and snippets.

@brunofurmon
Created January 27, 2017 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunofurmon/dda6a62f4d1a61db56a554fcdae712ed to your computer and use it in GitHub Desktop.
Save brunofurmon/dda6a62f4d1a61db56a554fcdae712ed to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
''' Node that carries an integer and a reference to its childs (Nodes)
'''
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def append(self, node):
self.children.append(node)
''' Returns sum of tree, pointed by the root node
'''
def sumTree(node):
if not node.children:
return node.data
sum = node.data
for child in node.children:
sum += sumTree(child)
return sum
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node1.append(node2)
node1.append(node4)
node2.append(node3)
node3.append(node5)
# 1
# |
# /\
# 2 4
# |
# 3
# |
# 5
print(sumTree(node1))
print(sumTree(node2))
print(sumTree(node3))
print(sumTree(node4))
print(sumTree(node5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment