Skip to content

Commit 2ccc0de

Browse files
Binary search tree
1 parent 0d5e266 commit 2ccc0de

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

tree/binary_search_tree.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
leverages recursive helper functions.
77
88
Binary Search Tree Implementation with Doctest Examples
9+
For more information on binary search trees, please see:
10+
https://en.wikipedia.org/wiki/Binary_search_tree
911
1012
To run the doctests:
1113
python -m doctest -v binary_search_tree.py
1214
"""
1315

16+
1417
class BSTNode:
1518
"""
1619
A node in the binary search tree.
@@ -24,17 +27,30 @@ class BSTNode:
2427
right : BSTNode or None
2528
The right child node.
2629
"""
30+
2731
def __init__(self, key: int) -> None:
32+
"""
33+
Initializes a new BST node.
34+
35+
Parameters
36+
----------
37+
key : int
38+
The key value for the new node.
39+
"""
2840
self.key = key
2941
self.left = None
3042
self.right = None
3143

3244

3345
class BinarySearchTree:
3446
"""
35-
Binary Search Tree (BST) class that supports operations such as
47+
Binary Search Tree (BST) class that supports basic operations such as
3648
insertion, search, deletion, and in-order traversal.
49+
50+
For details on BSTs, see:
51+
https://en.wikipedia.org/wiki/Binary_search_tree
3752
"""
53+
3854
def __init__(self) -> None:
3955
"""
4056
Initializes an empty Binary Search Tree.
@@ -73,7 +89,7 @@ def _insert_recursive(self, node: BSTNode, key: int) -> None:
7389
node : BSTNode
7490
The current node in the BST.
7591
key : int
76-
The key to insert.
92+
The key to be inserted.
7793
7894
Examples
7995
--------
@@ -124,14 +140,15 @@ def inorder_traversal(self) -> list:
124140

125141
def _inorder_recursive(self, node: BSTNode, result: list) -> None:
126142
"""
127-
Helper function for recursively performing in-order traversal by accumulating the keys.
143+
Helper function for recursively performing in-order traversal by
144+
accumulating the keys in the provided list.
128145
129146
Parameters
130147
----------
131148
node : BSTNode or None
132149
The current node being visited.
133150
result : list
134-
The list accumulating the keys.
151+
The list to accumulate the keys.
135152
136153
Examples
137154
--------
@@ -263,6 +280,7 @@ def _delete_recursive(self, node: BSTNode, key: int):
263280
>>> bst.root = BSTNode(10)
264281
>>> bst.root.left = BSTNode(5)
265282
>>> bst.root.right = BSTNode(15)
283+
>>> # Deleting a node in this simple tree; the new root will be unchanged as 10.
266284
>>> bst._delete_recursive(bst.root, 5).key
267285
10
268286
"""
@@ -293,7 +311,7 @@ def _find_min(self, node: BSTNode) -> BSTNode:
293311
Parameters
294312
----------
295313
node : BSTNode
296-
The root of the subtree.
314+
The root of the subtree from which to find the minimum key.
297315
298316
Returns
299317
-------

0 commit comments

Comments
 (0)