mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-30 16:31:08 +00:00
07e991d553
* ci(pre-commit): Add pep8-naming to `pre-commit` hooks (#7038) * refactor: Fix naming conventions (#7038) * Update arithmetic_analysis/lu_decomposition.py Co-authored-by: Christian Clauss <cclauss@me.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor(lu_decomposition): Replace `NDArray` with `ArrayLike` (#7038) * chore: Fix naming conventions in doctests (#7038) * fix: Temporarily disable project euler problem 104 (#7069) * chore: Fix naming conventions in doctests (#7038) Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.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]))
|