-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
serialize deserialize binary tree #9625
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
Merged
cclauss
merged 5 commits into
TheAlgorithms:master
from
AVAniketh0905:ser-deser-binary-tree
Oct 29, 2023
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cef886c
added serialize and desrialize bin tree
AVAniketh0905 5923c92
format files
AVAniketh0905 2e10621
added type hints
AVAniketh0905 44ec94d
added type hints
AVAniketh0905 7cc2602
Use dataclass .__eq__(), .__iter__(), and .__repr__()
cclauss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
155 changes: 155 additions & 0 deletions
155
data_structures/binary_tree/serialize_deserialize_binary_tree.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
from __future__ import annotations | ||
|
||
|
||
class TreeNode: | ||
""" | ||
A binary tree node has a value, left child, and right child. | ||
|
||
Props: | ||
val(int): The value of the node. | ||
left: The left child of the node. | ||
right: The right child of the node. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
val: int = 0, | ||
left: TreeNode | None = None, | ||
right: TreeNode | None = None, | ||
) -> None: | ||
if not isinstance(val, int): | ||
raise TypeError("Value must be an integer.") | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
|
||
# Helper functions | ||
def are_trees_identical(root1: TreeNode | None, root2: TreeNode | None) -> bool: | ||
""" | ||
Check if two binary trees are identical. | ||
|
||
Args: | ||
root1 (TreeNode): Tree 1 | ||
root2 (TreeNode): Tree 2 | ||
|
||
Returns: | ||
bool: True if the trees are identical, False otherwise. | ||
|
||
>>> root1 = TreeNode(1) | ||
>>> root1.left = TreeNode(2) | ||
>>> root1.right = TreeNode(3) | ||
>>> root2 = TreeNode(1) | ||
>>> root2.left = TreeNode(2) | ||
>>> root2.right = TreeNode(3) | ||
>>> are_trees_identical(root1, root2) | ||
True | ||
>>> root1 = TreeNode(1) | ||
>>> root1.left = TreeNode(2) | ||
>>> root1.right = TreeNode(3) | ||
>>> root2 = TreeNode(1) | ||
>>> root2.left = TreeNode(2) | ||
>>> root2.right = TreeNode(4) | ||
>>> are_trees_identical(root1, root2) | ||
False | ||
""" | ||
|
||
if not root1 and not root2: | ||
return True | ||
if not root1 or not root2: | ||
return False | ||
|
||
return ( | ||
root1.val == root2.val | ||
and are_trees_identical(root1.left, root2.left) | ||
and are_trees_identical(root1.right, root2.right) | ||
) | ||
|
||
|
||
# Main functions | ||
def serialize(root: TreeNode | None) -> str: | ||
""" | ||
Serialize a binary tree to a string using preorder traversal. | ||
|
||
Args: | ||
root(TreeNode): The root of the binary tree. | ||
|
||
Returns: | ||
A string representation of the binary tree. | ||
|
||
>>> root = TreeNode(1) | ||
>>> root.left = TreeNode(2) | ||
>>> root.right = TreeNode(3) | ||
>>> root.right.left = TreeNode(4) | ||
>>> root.right.right = TreeNode(5) | ||
>>> serialize(root) | ||
'1,2,null,null,3,4,null,null,5,null,null' | ||
>>> root = TreeNode(1) | ||
>>> serialize(root) | ||
'1,null,null' | ||
""" | ||
|
||
# Use "null" to represent empty nodes in the serialization | ||
if not root: | ||
return "null" | ||
|
||
return str(root.val) + "," + serialize(root.left) + "," + serialize(root.right) | ||
|
||
|
||
def deserialize(data: str) -> TreeNode | None: | ||
""" | ||
Deserialize a string to a binary tree. | ||
|
||
Args: | ||
data(str): The serialized string. | ||
|
||
Returns: | ||
The root of the binary tree. | ||
|
||
>>> root = TreeNode(1) | ||
>>> root.left = TreeNode(2) | ||
>>> root.right = TreeNode(3) | ||
>>> root.right.left = TreeNode(4) | ||
>>> root.right.right = TreeNode(5) | ||
>>> serialzed_data = serialize(root) | ||
>>> deserialized = deserialize(serialzed_data) | ||
>>> are_trees_identical(root, deserialized) | ||
True | ||
>>> root = TreeNode(1) | ||
>>> serialzed_data = serialize(root) | ||
>>> dummy_data = "1,2,null,null,3,4,null,null,5,null,null" | ||
>>> deserialized = deserialize(dummy_data) | ||
>>> are_trees_identical(root, deserialized) | ||
False | ||
>>> deserialize("") | ||
Traceback (most recent call last): | ||
... | ||
ValueError: Data cannot be empty. | ||
""" | ||
|
||
if data == "": | ||
raise ValueError("Data cannot be empty.") | ||
|
||
# Split the serialized string by comma to get node values | ||
nodes = data.split(",") | ||
|
||
def build_tree() -> TreeNode | None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file |
||
# Get the next value from the list | ||
val = nodes.pop(0) | ||
|
||
if val == "null": | ||
return None | ||
|
||
node = TreeNode(int(val)) | ||
node.left = build_tree() # Recursively build left subtree | ||
node.right = build_tree() # Recursively build right subtree | ||
|
||
return node | ||
|
||
return build_tree() | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
data_structures/binary_tree/serialize_deserialize_binary_tree.py
, please provide doctest for the functionbuild_tree