Created
January 27, 2017 02:31
-
-
Save brunofurmon/dda6a62f4d1a61db56a554fcdae712ed to your computer and use it in GitHub Desktop.
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
#!/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