Skip to content

Commit a5ec4ec

Browse files
committed
Added tree implementations with lists and OOP
1 parent 627ad21 commit a5ec4ec

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Trees/implement-with-OOP.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
class BinaryTree(object):
3+
4+
def __init__(self, value):
5+
self.key = value
6+
self.leftChild = None
7+
self.rightChild = None
8+
9+
def insertLeft(self, newNode):
10+
11+
if self.leftChild == None:
12+
self.leftChild = BinaryTree(newNode)
13+
else:
14+
t = BinaryTree(newNode)
15+
t.leftChild = self.leftChild
16+
self.leftChild = t
17+
18+
def insertRight(self, newNode):
19+
20+
if self.rightChild == None:
21+
self.rightChild = BinaryTree(newNode)
22+
else:
23+
t = BinaryTree(newNode)
24+
t.rightChild = self.rightChild
25+
self.rightChild = t
26+
27+
def getLeftChild(self):
28+
return self.leftChild
29+
30+
def getRightChild(self):
31+
return self.rightChild
32+
33+
def setRootVal(self, val):
34+
self.key = val
35+
36+
def getRootVal(self):
37+
return self.key

Trees/implement-with-list-of-lists.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
def BinaryTree(r):
3+
return [r, [], []]
4+
5+
def insertLeft(root, newBranch):
6+
t = root.pop(1)
7+
8+
if len(t) > 1:
9+
root.insert(1, [newBranch, t, []])
10+
else:
11+
root.insert(1, [newBranch, [], []])
12+
return root
13+
14+
def insertRight(root, newBranch):
15+
t = root.pop(2)
16+
17+
if len(t) > 1:
18+
root.insert(2, [newBranch, [], t])
19+
else:
20+
root.insert(2, [newBranch, [], []])
21+
return root
22+
23+
def getRootVal(root):
24+
return root[0]
25+
26+
def setRootVal(root, newVal):
27+
root[0] = newVal
28+
29+
def getLeftChild(root):
30+
return root[1]
31+
32+
def getRightChild(root):
33+
return root[2]
34+
35+

0 commit comments

Comments
 (0)