Skip to content

Commit 44ec94d

Browse files
committed
added type hints
1 parent 2e10621 commit 44ec94d

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

Diff for: data_structures/binary_tree/serialize_deserialize_binary_tree.py

+18-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
34
class TreeNode:
45
"""
56
A binary tree node has a value, left child, and right child.
@@ -10,7 +11,12 @@ class TreeNode:
1011
right: The right child of the node.
1112
"""
1213

13-
def __init__(self, val: int = 0, left:TreeNode = None, right:TreeNode = None) -> None:
14+
def __init__(
15+
self,
16+
val: int = 0,
17+
left: TreeNode | None = None,
18+
right: TreeNode | None = None,
19+
) -> None:
1420
if not isinstance(val, int):
1521
raise TypeError("Value must be an integer.")
1622
self.val = val
@@ -19,7 +25,7 @@ def __init__(self, val: int = 0, left:TreeNode = None, right:TreeNode = None) ->
1925

2026

2127
# Helper functions
22-
def are_trees_identical(root1: TreeNode, root2: TreeNode) -> bool:
28+
def are_trees_identical(root1: TreeNode | None, root2: TreeNode | None) -> bool:
2329
"""
2430
Check if two binary trees are identical.
2531
@@ -61,7 +67,7 @@ def are_trees_identical(root1: TreeNode, root2: TreeNode) -> bool:
6167

6268

6369
# Main functions
64-
def serialize(root: TreeNode) -> str:
70+
def serialize(root: TreeNode | None) -> str:
6571
"""
6672
Serialize a binary tree to a string using preorder traversal.
6773
@@ -90,7 +96,7 @@ def serialize(root: TreeNode) -> str:
9096
return str(root.val) + "," + serialize(root.left) + "," + serialize(root.right)
9197

9298

93-
def deserialize(data: str) -> TreeNode:
99+
def deserialize(data: str) -> TreeNode | None:
94100
"""
95101
Deserialize a string to a binary tree.
96102
@@ -115,12 +121,19 @@ def deserialize(data: str) -> TreeNode:
115121
>>> deserialized = deserialize(dummy_data)
116122
>>> are_trees_identical(root, deserialized)
117123
False
124+
>>> deserialize("")
125+
Traceback (most recent call last):
126+
...
127+
ValueError: Data cannot be empty.
118128
"""
119129

130+
if data == "":
131+
raise ValueError("Data cannot be empty.")
132+
120133
# Split the serialized string by comma to get node values
121134
nodes = data.split(",")
122135

123-
def build_tree() -> TreeNode:
136+
def build_tree() -> TreeNode | None:
124137
# Get the next value from the list
125138
val = nodes.pop(0)
126139

0 commit comments

Comments
 (0)