Skip to content

Commit 37ae3b8

Browse files
committed
add helper
1 parent 5d41dc0 commit 37ae3b8

File tree

1 file changed

+49
-12
lines changed

1 file changed

+49
-12
lines changed

helper.rb

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,44 @@ def initialize(val)
77
end
88
end
99

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}
1148
def deserialize(data)
1249
return data if data.nil?
1350
q=[]
@@ -20,16 +57,16 @@ def deserialize(data)
2057
l = data.shift
2158
r = data.shift
2259

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
2764

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
3269

33-
end
34-
root
35-
end
70+
end
71+
root
72+
end

0 commit comments

Comments
 (0)