-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree.py
55 lines (42 loc) · 975 Bytes
/
binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from tree import TreeNode
class BinaryTreeNode(TreeNode):
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None
self.children = []
def insert(self, child):
if self.left == None:
self.left = child
self.children.append(child)
child.parent = self
elif self.right == None:
self.right = child
self.children.append(child)
child.parent = self
else:
print('You cannot insert', child.data, 'here.')
def inorder(self):
output = []
if self.left != None:
output += self.left.inorder()
output.append(self.data)
if self.right != None:
output += self.right.inorder()
return output
if __name__ == '__main__':
a = BinaryTreeNode('3')
b = BinaryTreeNode('2')
c = BinaryTreeNode('7')
d = BinaryTreeNode('5')
e = BinaryTreeNode('8')
f = BinaryTreeNode('4')
g = BinaryTreeNode('6')
a.insert(b)
a.insert(c)
c.insert(d)
c.insert(e)
d.insert(f)
d.insert(g)
print(a.tree())