File tree Expand file tree Collapse file tree 1 file changed +49
-12
lines changed Expand file tree Collapse file tree 1 file changed +49
-12
lines changed Original file line number Diff line number Diff line change @@ -7,7 +7,44 @@ def initialize(val)
7
7
end
8
8
end
9
9
10
- # Deserialize string to root object
10
+ # Encodes a tree to a single string.
11
+ #
12
+ # @param {TreeNode} root
13
+ # @return {string}
14
+ def serialize ( root )
15
+ q = [ ]
16
+ ans = [ ]
17
+ return root if root . nil?
18
+
19
+ q . push ( root )
20
+ until q . empty?
21
+ t = q . shift
22
+ if t . nil?
23
+ ans . push ( nil )
24
+ else
25
+ ans . push ( t . val )
26
+
27
+ if t . left . nil?
28
+ q . push ( nil )
29
+ else
30
+ q . push ( t . left )
31
+ end
32
+
33
+ if t . right . nil?
34
+ q . push ( nil )
35
+ else
36
+ q . push ( t . right )
37
+ end
38
+ end
39
+
40
+ end
41
+ ans
42
+ end
43
+
44
+ # Decodes your encoded data to tree.
45
+ #
46
+ # @param {string} data
47
+ # @return {TreeNode}
11
48
def deserialize ( data )
12
49
return data if data . nil?
13
50
q = [ ]
@@ -20,16 +57,16 @@ def deserialize(data)
20
57
l = data . shift
21
58
r = data . shift
22
59
23
- unless l . nil?
24
- t . left = TreeNode . new ( l )
25
- q . push ( t . left )
26
- end
60
+ unless l . nil?
61
+ t . left = TreeNode . new ( l )
62
+ q . push ( t . left )
63
+ end
27
64
28
- unless r . nil?
29
- t . right = TreeNode . new ( r )
30
- q . push ( t . right )
31
- end
65
+ unless r . nil?
66
+ t . right = TreeNode . new ( r )
67
+ q . push ( t . right )
68
+ end
32
69
33
- end
34
- root
35
- end
70
+ end
71
+ root
72
+ end
You can’t perform that action at this time.
0 commit comments