2019-07-01 08:10:18 +00:00
|
|
|
"""
|
|
|
|
Tree_sort algorithm.
|
|
|
|
|
|
|
|
Build a BST and in order traverse.
|
|
|
|
"""
|
|
|
|
|
2018-03-04 02:27:05 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
class Node:
|
2018-03-04 02:27:05 +00:00
|
|
|
# BST data structure
|
|
|
|
def __init__(self, val):
|
|
|
|
self.val = val
|
2019-07-01 08:10:18 +00:00
|
|
|
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:
|
2018-10-17 21:28:57 +00:00
|
|
|
if self.left is None:
|
2022-10-12 22:54:20 +00:00
|
|
|
self.left = Node(val)
|
2018-03-04 02:27:05 +00:00
|
|
|
else:
|
|
|
|
self.left.insert(val)
|
|
|
|
elif val > self.val:
|
2018-10-17 21:28:57 +00:00
|
|
|
if self.right is None:
|
2022-10-12 22:54:20 +00:00
|
|
|
self.right = Node(val)
|
2018-03-04 02:27:05 +00:00
|
|
|
else:
|
|
|
|
self.right.insert(val)
|
|
|
|
else:
|
|
|
|
self.val = val
|
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2018-03-04 02:27:05 +00:00
|
|
|
def inorder(root, res):
|
2020-05-21 19:50:52 +00:00
|
|
|
# Recursive traversal
|
2018-03-04 02:27:05 +00:00
|
|
|
if root:
|
2019-07-01 08:10:18 +00:00
|
|
|
inorder(root.left, res)
|
2018-03-04 02:27:05 +00:00
|
|
|
res.append(root.val)
|
2019-07-01 08:10:18 +00:00
|
|
|
inorder(root.right, res)
|
|
|
|
|
2018-03-04 02:27:05 +00:00
|
|
|
|
2019-05-25 13:41:24 +00:00
|
|
|
def tree_sort(arr):
|
2018-03-04 02:27:05 +00:00
|
|
|
# Build BST
|
|
|
|
if len(arr) == 0:
|
|
|
|
return arr
|
2022-10-12 22:54:20 +00:00
|
|
|
root = Node(arr[0])
|
2019-07-01 08:10:18 +00:00
|
|
|
for i in range(1, len(arr)):
|
2018-03-04 02:27:05 +00:00
|
|
|
root.insert(arr[i])
|
2019-07-01 08:10:18 +00:00
|
|
|
# Traverse BST in order.
|
2018-03-04 02:27:05 +00:00
|
|
|
res = []
|
2019-07-01 08:10:18 +00:00
|
|
|
inorder(root, res)
|
2018-03-04 02:27:05 +00:00
|
|
|
return res
|
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2019-07-01 08:10:18 +00:00
|
|
|
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
|