mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
21ed8968c0
* implement bidirectional astar * add type hints * add wikipedia url * format with black * changes from review * fix collision check * Add testmod() * # doctest: +NORMALIZE_WHITESPACE * Codespell: euclidean * Codespell: coordinates * Codespell: traversal * Codespell: remaining Co-authored-by: John Law <johnlaw.po@gmail.com> Co-authored-by: Christian Clauss <cclauss@me.com>
54 lines
1.1 KiB
Python
54 lines
1.1 KiB
Python
"""
|
|
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 traversal
|
|
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]))
|