-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathtree.py
61 lines (47 loc) · 1011 Bytes
/
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
55
56
57
58
59
60
61
# Python3 program to
# implement Tree Sort
# Class containing left and
# right child of current
# node and key value
class Node:
def __init__(self,item = 0):
self.key = item
self.left,self.right = None,None
# Root of BST
root = Node()
root = None
# This method mainly
# calls insertRec()
def insert(key):
global root
root = insertRec(root, key)
# A recursive function to
# insert a new key in BST
def insertRec(root, key):
# If the tree is empty,
# return a new node
if (root == None):
root = Node(key)
return root
# Otherwise, recur
# down the tree
if (key < root.key):
root.left = insertRec(root.left, key)
elif (key > root.key):
root.right = insertRec(root.right, key)
# return the root
return root
# A function to do
# inorder traversal of BST
def inorderRec(root):
if (root != None):
inorderRec(root.left)
print(root.key ,end = " ")
inorderRec(root.right)
def treeins(arr):
for i in range(len(arr)):
insert(arr[i])
# Driver Code
arr = [5, 4, 7, 2, 11]
treeins(arr)
inorderRec(root)