feat: implement inorder traversal of ranked tree
Fixes #4 Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
6fb09cd89b
commit
d4d0b65f45
2 changed files with 29 additions and 2 deletions
21
node.py
21
node.py
|
@ -1,6 +1,14 @@
|
|||
from abc import abstractmethod
|
||||
import enum
|
||||
from typing import Callable, Optional, Generic, Tuple, TypeVar, Protocol
|
||||
from typing import (
|
||||
Callable,
|
||||
Iterable,
|
||||
Optional,
|
||||
Generic,
|
||||
Tuple,
|
||||
TypeVar,
|
||||
Protocol,
|
||||
)
|
||||
|
||||
|
||||
class Comparable(Protocol):
|
||||
|
@ -54,6 +62,17 @@ class Node(Generic[T]):
|
|||
def __str__(self) -> str:
|
||||
return f"Node(value={self.value}, rank={self.rank})"
|
||||
|
||||
def __iter__(self) -> Iterable[T]:
|
||||
"""
|
||||
Yields:
|
||||
Keys from the subtree rooted at the node in an inorder fashion.
|
||||
"""
|
||||
if self.left:
|
||||
yield from self.left
|
||||
yield self.value
|
||||
if self.right:
|
||||
yield from self.right
|
||||
|
||||
@staticmethod
|
||||
def height(node: "Optional[Node[T]]") -> int:
|
||||
return (
|
||||
|
|
|
@ -3,7 +3,7 @@ from node import Node, Comparable
|
|||
from abc import abstractmethod
|
||||
from collections import deque
|
||||
import logging
|
||||
from typing import Deque, Optional, Tuple, TypeVar, Generic
|
||||
from typing import Deque, Iterable, Optional, Tuple, TypeVar, Generic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
T = TypeVar("T", bound=Comparable)
|
||||
|
@ -140,3 +140,11 @@ class RankedTree(Generic[T]):
|
|||
if to_be_rebalanced := self._delete(value):
|
||||
y, parent = to_be_rebalanced
|
||||
self._delete_rebalance(y, parent)
|
||||
|
||||
def __iter__(self) -> Iterable[T]:
|
||||
"""
|
||||
Yields:
|
||||
Keys from the tree in an inorder fashion.
|
||||
"""
|
||||
if self.root:
|
||||
yield from self.root
|
||||
|
|
Loading…
Reference in a new issue