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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
Next Next 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 e9c7bacf29dcbc6afe9288109510f371f3cdf0b6
20 changes: 11 additions & 9 deletions sorts/tree_sort.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass

Check failure on line 3 in sorts/tree_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

sorts/tree_sort.py:1:1: I001 Import block is un-sorted or un-formatted


@dataclass
class Node:
"""Node of a Binary Search Tree (BST) for sorting."""

val: int
left: Node | None = None
right: Node | None = None
Expand All @@ -14,10 +16,10 @@
# 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 @@ -31,8 +33,8 @@
else:
self.left.insert(val)
# Values > current go to right subtree
else:
if self.right is None:

Check failure on line 37 in sorts/tree_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR5501)

sorts/tree_sort.py:36:9: PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation
self.right = Node(val)
else:
self.right.insert(val)
Expand All @@ -41,13 +43,13 @@
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 @@ -67,16 +69,16 @@
# 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)
Loading