Binary Tree¶
py_ds.datastructures.trees.base.BinaryTree
¶
Bases: ABC, Generic[T]
Initialize a binary tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[T] | None
|
Optional iterable of items to insert into the tree. If None, an empty tree is created. |
None
|
Source code in src/py_ds/datastructures/trees/base.py
Attributes¶
is_empty
property
¶
Check if the tree is empty.
Returns:
| Type | Description |
|---|---|
bool
|
True if the tree contains no elements, False otherwise. |
height
property
¶
Get the height of the tree.
Returns:
| Type | Description |
|---|---|
int
|
The height of the tree. Returns -1 for an empty tree, 0 for a tree |
int
|
with only a root node, and increases by 1 for each level below. |
Functions¶
insert
abstractmethod
¶
Add a value to the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The value to insert into the tree. |
required |
remove
abstractmethod
¶
Remove a value from the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The value to remove from the tree. |
required |
clear
¶
__len__
¶
Return the number of elements in the tree.
Returns:
| Type | Description |
|---|---|
int
|
The number of elements in the tree. |
inorder
¶
Traverse the tree in inorder (left, root, right).
Yields:
| Type | Description |
|---|---|
T
|
Values from the tree in inorder traversal order. |
Source code in src/py_ds/datastructures/trees/base.py
preorder
¶
Traverse the tree in preorder (root, left, right).
Yields:
| Type | Description |
|---|---|
T
|
Values from the tree in preorder traversal order. |
Source code in src/py_ds/datastructures/trees/base.py
postorder
¶
Traverse the tree in postorder (left, right, root).
Yields:
| Type | Description |
|---|---|
T
|
Values from the tree in postorder traversal order. |
Source code in src/py_ds/datastructures/trees/base.py
level_order
¶
Traverse the tree in level-order (breadth-first).
Yields:
| Type | Description |
|---|---|
T
|
Values from the tree in level-order traversal, from top to bottom |
T
|
and left to right at each level. |
Source code in src/py_ds/datastructures/trees/base.py
__str__
¶
Return a string representation of the tree.
Returns:
| Type | Description |
|---|---|
str
|
A visual string representation of the tree structure. Returns 'EMPTY' |
str
|
if the tree is empty. |