-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path449_serialize_and_deserialize_bst.rb
58 lines (42 loc) · 1.05 KB
/
449_serialize_and_deserialize_bst.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true
# https://leetcode.com/problems/serialize-and-deserialize-bst/
# @param {TreeNode} root
# @return {String}
def serialize(root)
return '#' unless root
result = []
result << root.val
left = serialize(root.left)
result << ','
result << left
right = serialize(root.right)
result << ','
result << right
result.join
end
# @param {String} data
# @return {TreeNode}
def deserialize(data)
raw_data = data.split(',')
deserialize_from_string(raw_data, 0, raw_data.size - 1)
end
# @param {String[]} data
# @param {Integer} l
# @param {Integer} r
# @return {TreeNode}
def deserialize_from_string(data, l, r)
return if data[l] == '#'
root = ::TreeNode.new(data[l].to_i)
built = false
((l + 1)..r).each do |i|
value = data[i]
next if value == '#'
next unless value.to_i > root.val
built = true
root.left = deserialize_from_string(data, l + 1, i - 1)
root.right = deserialize_from_string(data, i, r)
break
end
root.left = deserialize_from_string(data, l + 1, r) unless built
root
end