data_structures.binary_tree.serialize_deserialize_binary_tree ============================================================= .. py:module:: data_structures.binary_tree.serialize_deserialize_binary_tree Classes ------- .. autoapisummary:: data_structures.binary_tree.serialize_deserialize_binary_tree.TreeNode Functions --------- .. autoapisummary:: data_structures.binary_tree.serialize_deserialize_binary_tree.deserialize Module Contents --------------- .. py:class:: TreeNode A binary tree node has a value, left child, and right child. Props: value: The value of the node. left: The left child of the node. right: The right child of the node. .. py:method:: __iter__() -> collections.abc.Iterator[TreeNode] Iterate through the tree in preorder. Returns: An iterator of the tree nodes. >>> list(TreeNode(1)) [1,null,null] >>> tuple(TreeNode(1, TreeNode(2), TreeNode(3))) (1,2,null,null,3,null,null, 2,null,null, 3,null,null) .. py:method:: __len__() -> int Count the number of nodes in the tree. Returns: The number of nodes in the tree. >>> len(TreeNode(1)) 1 >>> len(TreeNode(1, TreeNode(2), TreeNode(3))) 3 .. py:method:: __post_init__() .. py:method:: __repr__() -> str Represent the tree as a string. Returns: A string representation of the tree. >>> repr(TreeNode(1)) '1,null,null' >>> repr(TreeNode(1, TreeNode(2), TreeNode(3))) '1,2,null,null,3,null,null' >>> repr(TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))) '1,2,null,null,3,4,null,null,5,null,null' .. py:method:: five_tree() -> TreeNode :classmethod: >>> repr(TreeNode.five_tree()) '1,2,null,null,3,4,null,null,5,null,null' .. py:attribute:: left :type: TreeNode | None :value: None .. py:attribute:: right :type: TreeNode | None :value: None .. py:attribute:: value :type: int :value: 0 .. py:function:: 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.five_tree() >>> serialzed_data = repr(root) >>> deserialized = deserialize(serialzed_data) >>> root == deserialized True >>> root is deserialized # two separate trees False >>> root.right.right.value = 6 >>> root == deserialized False >>> serialzed_data = repr(root) >>> deserialized = deserialize(serialzed_data) >>> root == deserialized True >>> deserialize("") Traceback (most recent call last): ... ValueError: Data cannot be empty.