File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
serialize-and-deserialize-binary-tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
2
+
3
+ # Definition for a binary tree node.
4
+ class TreeNode (object ):
5
+ def __init__ (self , x ):
6
+ self .val = x
7
+ self .left = None
8
+ self .right = None
9
+
10
+ class Codec :
11
+
12
+ def serialize (self , root ):
13
+ """Encodes a tree to a single string.
14
+
15
+ :type root: TreeNode
16
+ :rtype: str
17
+ """
18
+ res = []
19
+
20
+ def preorder_ser (node ):
21
+ # base condition
22
+ if not node :
23
+ res .append ("None" )
24
+ return
25
+
26
+ # traversal
27
+ res .append (str (node .val ))
28
+ preorder_ser (node .left )
29
+ preorder_ser (node .right )
30
+
31
+ preorder_ser (root )
32
+
33
+ return "," .join (res )
34
+
35
+ def deserialize (self , data ):
36
+ """Decodes your encoded data to tree.
37
+
38
+ :type data: str
39
+ :rtype: TreeNode
40
+ """
41
+ from collections import deque
42
+
43
+ preorder_vals = deque (data .split ("," ))
44
+
45
+ def preorder_deser ():
46
+ val = preorder_vals .popleft ()
47
+
48
+ # base condition
49
+ if val == "None" :
50
+ return None
51
+
52
+ # traversal
53
+ node = TreeNode (int (val ))
54
+ node .left = preorder_deser ()
55
+ node .right = preorder_deser ()
56
+
57
+ return node
58
+
59
+ return preorder_deser ()
60
+
61
+ # Your Codec object will be instantiated and called as such:
62
+ # ser = Codec()
63
+ # deser = Codec()
64
+ # ans = deser.deserialize(ser.serialize(root))
You can’t perform that action at this time.
0 commit comments