forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree_sort.py
46 lines (41 loc) · 1.09 KB
/
tree_sort.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
# Tree_sort algorithm
# Build a BST and in order traverse.
class node():
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self,val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive travesal
if root:
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
def tree_sort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1,len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root,res)
return res
if __name__ == '__main__':
print(tree_sort([10,1,3,2,9,14,13]))