Skip to content

Commit 2bad5c1

Browse files
authored
BST treversal
Creates a tree of given values and gives inorder, preorder and postorder of a tree.
1 parent e1fe0e0 commit 2bad5c1

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

TreeTravesal.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
2+
3+
class Node(object):
4+
"""docstring for Node"""
5+
def __init__(self, val):
6+
self.key = val
7+
self.left=None
8+
self.right=None
9+
10+
11+
class Tree:
12+
"""docstring for Tree"""
13+
def __init__(self,val):
14+
self.root = Node(val)
15+
16+
def insertNode(root,val):
17+
if(root==None):
18+
root=Node(val)
19+
elif(root.key<val):
20+
root.right=Tree.insertNode(root.right,val)
21+
else:
22+
root.left=Tree.insertNode(root.left,val)
23+
return root
24+
25+
def inorder(root):
26+
if(root==None):
27+
return
28+
else:
29+
Tree.inorder(root.left)
30+
print(root.key)
31+
Tree.inorder(root.right)
32+
33+
def preorder(root):
34+
if(root==None):
35+
return
36+
else:
37+
print(root.key)
38+
Tree.preorder(root.left)
39+
Tree.preorder(root.right)
40+
41+
def postorder(root):
42+
if(root==None):
43+
return
44+
else:
45+
Tree.postorder(root.left)
46+
Tree.postorder(root.right)
47+
print(root.key)
48+
49+
50+
51+
array=[1,22,3,44,32,35]
52+
treeRoot=Node(array[0])
53+
for i in range(1,len(array)):
54+
treeRoot=Tree.insertNode(treeRoot,array[i])
55+
56+
Tree.inorder(treeRoot)
57+
Tree.preorder(treeRoot)
58+
Tree.postorder(treeRoot)
59+
60+
61+
62+

0 commit comments

Comments
 (0)