-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathBinaryTree.py
107 lines (94 loc) · 2.24 KB
/
BinaryTree.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'''
This file contains all tree traversal and level wise insertion in tree
'''
import queue
'''class for node of binary tree'''
class Node(object):
"""docstring for Node"""
def __init__(self, val=None):
super(Node, self).__init__()
self.left = None
self.right = None
self.val = val
'''class for binary tree'''
class BinaryTree(object):
"""docstring for BinaryTree"""
def __init__(self):
super(BinaryTree, self).__init__()
self.root = None
'''Insert node level wise'''
def insert(self, val):
new_node = Node(val)
if self.root is None:
self.root = new_node
return
Q = queue.Queue(maxsize=20)
Q.put(self.root) #Enqueue
while(Q.empty() is not True):
temp = Q.get() #Dequeue
if temp.left:
Q.put(temp.left)
else:
temp.left = new_node
Q.queue.clear()
return
if temp.right:
Q.put(temp.right)
else:
temp.right = new_node
Q.queue.clear()
return
Q.queue.clear()
'''Inorder Traversal'''
def inorder(self,root):
res = []
if root:
res = self.inorder(root.left)
res.append(root.val)
res = res + self.inorder(root.right)
return res
'''Preorder Traversal'''
def preorder(self,root):
res = []
if root:
res.append(root.val)
res = res + self.preorder(root.left)
res = res + self.preorder(root.right)
return res
'''Postorder Traversal'''
def postorder(self,root):
res = []
if root:
res = self.postorder(root.left)
res = res + self.postorder(root.right)
res.append(root.val)
return res
'''Level Order Traversal'''
def levelorder(self,root):
res = []
if root is None:
return res
Q = queue.Queue(maxsize=20)
Q.put(root)
while(Q.empty() is not True):
#print(list(Q.queue),res)
temp = Q.get()
res.append(temp.val)
if temp.left:
Q.put(temp.left)
if temp.right:
Q.put(temp.right)
Q.queue.clear()
return res
if __name__ == '__main__':
btree = BinaryTree()
btree.root = Node(1)
btree.root.left =Node(2)
btree.root.right = Node(3)
btree.insert(4)
btree.insert(5)
btree.insert(6)
print(btree.preorder(btree.root))
print(btree.inorder(btree.root))
print(btree.postorder(btree.root))
print(btree.levelorder(btree.root))