''' Binary Trees: One method: using lists of lists, e.g. a_tree = [root, [left child, child, child][right]] List implementation: insert_rightt = creates a whole nother tree (recursive)''' class ListBinaryTree: #list just one implementation def __init__(self, value): self.node = [value, None, None] def __str__: #used by print() n = self.node return '[' + n[0] + ',' + str(n[1]) + ',' + str(n[2]) + ']' #is recursive, str being called #prints all children of all nodes #works through recurisvley #eg print(tree_obj) = [59, [4, [7, None, None],None], [6, [5, None, None], [2, None, None]]] class RefBinaryTree: #storing links, like linked list def __init__(self, data): #each node contains links to left and right child self.data = data self.left = None self.right = None def insert_left(self, data): #creates a new node with data, inserts binary tree object t = RefBinaryTree(data) if self.left == None: #if no pointer make new self.left = t else: t.left = self.left #points old left child to new left child self.left = t def create_string(self, indent): #55---+ info = data if there is a left child: add to info, add the (l) and newline, and call again with increased indent same for right child: same return the info #(l) 4---+ #(l) 5 ---+ #(r) 6---+ #recursive, each call increases indent #if r = None, r = False, if not None, r = True def get_node_sum(self): sums = 0 sums = self.key if self == None: #wont work of tree = None return 0 if self.left: sums += get_node_sum(self.left) get_node_sum(self.left) sums += self.get_value() #python can set defaults for argument e.g. def foo(x,y,z=2,a=None) named parameters return sums
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question