Serialize and Deserialize Binary Tree

by atalaykutlay

Solution to "Serialize and Deserialize Binary Tree" question on Leetcode.

Serialize and Deserialize Binary Tree
1class Codec:
2
3    def serialize(self, root):
4        """Encodes a tree to a single string.
5        
6        :type root: TreeNode
7        :rtype: str
8        """
9        if root is None:
10            return ""
11        
12        result = [str(root.val)]
13        nodes = collections.deque([root])
14
15        while len(nodes) > 0:
16            node = nodes.popleft()
17            
18            if node.left:
19                nodes.append(node.left)
20                result.append(str(node.left.val))
21            else:
22                result.append("null")
23            
24            if node.right:
25                nodes.append(node.right)
26                result.append(str(node.right.val))
27            else:
28                result.append("null")
29        
30        return ",".join(result)
31
32    def deserialize(self, data):
33        """Decodes your encoded data to tree.
34        
35        :type data: str
36        :rtype: TreeNode
37        """
38        if len(data) == 0:
39            return None
40        nodes = data.split(",")
41    
42        root = TreeNode(nodes[0])
43        assignments = collections.deque([root])
44        i = 1
45        while len(assignments) > 0:
46            node = assignments.popleft()
47            if i < len(nodes) and nodes[i] != "null":
48                node.left = TreeNode(nodes[i])
49                assignments.append(node.left)
50            i += 1
51            if i < len(nodes) and nodes[i] != "null":
52                node.right = TreeNode(nodes[i])
53                assignments.append(node.right)
54            i += 1
55        return root
56            
57

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago