10000 Fix Tree Sort algorithm for duplicate values and input types by lighting9999 · Pull Request #12786 · TheAlgorithms/Python · GitHub
[go: up one dir, main page]

Skip to content

Fix Tree Sort algorithm for duplicate values and input types #12786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jun 7, 2025
commit e113d53141b58fadb2d3a667aaf4bba3556f85dd
19 changes: 10 additions & 9 deletions sorts/tree_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
@dataclass
class Node:
"""Node of a Binary Search Tree (BST) for sorting."""

val: int
left: Node | None = None
right: Node | None = None
Expand All @@ -16,10 +17,10 @@ def __iter__(self) -> Iterator[int]:
# Traverse left subtree first (smaller values)
if self.left:
yield from self.left

# Current node value
yield self.val

# Traverse right subtree last (larger values)
if self.right:
yield from self.right
Expand All @@ -42,13 +43,13 @@ def insert(self, val: int) -> None:
def tree_sort(arr: list[int] | tuple[int, ...]) -> tuple[int, ...]:
"""
Sort sequence using Binary Search Tree (BST) traversal.

Args:
arr: Input sequence (list or tuple of integers)

Returns:
Tuple of sorted integers

Examples:
>>> tree_sort([])
()
Expand All @@ -68,16 +69,16 @@ def tree_sort(arr: list[int] | tuple[int, ...]) -> tuple[int, ...]:
# Handle empty input immediately
if not arr:
return ()

# Convert to list for uniform processing
items = list(arr)

# Initialize BST root with first element
root = Node(items[0])

# Insert remaining items into BST
for item in items[1:]:
root.insert(item)

# Convert BST traversal to sorted tuple
return tuple(root)
0