Python/sorts/tree_sort.py

54 lines
1.1 KiB
Python
Raw Normal View History

"""
Tree_sort algorithm.
Build a BST and in order traverse.
"""
2018-03-04 02:27:05 +00:00
class node():
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, val):
2018-03-04 02:27:05 +00:00
if self.val:
if val < self.val:
if self.left is None:
2018-03-04 02:27:05 +00:00
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
2018-03-04 02:27:05 +00:00
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
2018-03-04 02:27:05 +00:00
def inorder(root, res):
# Recursive travesal
2018-03-04 02:27:05 +00:00
if root:
inorder(root.left, res)
2018-03-04 02:27:05 +00:00
res.append(root.val)
inorder(root.right, res)
2018-03-04 02:27:05 +00:00
def tree_sort(arr):
2018-03-04 02:27:05 +00:00
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1, len(arr)):
2018-03-04 02:27:05 +00:00
root.insert(arr[i])
# Traverse BST in order.
2018-03-04 02:27:05 +00:00
res = []
inorder(root, res)
2018-03-04 02:27:05 +00:00
return res
if __name__ == '__main__':
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))