-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem44.cs
More file actions
76 lines (66 loc) · 1.9 KB
/
Problem44.cs
File metadata and controls
76 lines (66 loc) · 1.9 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
namespace LeetCode;
using System.Globalization;
/// <summary>
/// <see href="https://leetcode.com/problems/serialize-and-deserialize-binary-tree/">Serialize and Deserialize Binary Tree</see>.
/// </summary>
public static class Problem44
{
/// <summary>
/// Encodes a tree to a single string.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="root">Binary tree to serialize.</param>
/// <returns>Serialized binary tree.</returns>
public static string Serialize(TreeNode? root)
{
if (root == null)
{
return string.Empty;
}
return $"{root.Val},{Serialize(root.Left)},{Serialize(root.Right)}";
}
/// <summary>
/// Decodes your encoded data to tree.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="data">Serialized binary tree.</param>
/// <returns>Deserialized binary tree.</returns>
public static TreeNode? Deserialize(string data)
{
if (string.IsNullOrEmpty(data))
{
return null;
}
var queue = new Queue<int?>();
for (int left = 0, right = 0; right < data.Length; right++)
{
if (data[right] == ',')
{
if (left < right)
{
queue.Enqueue(int.Parse(data[left..right], CultureInfo.CurrentCulture));
}
else
{
queue.Enqueue(null);
}
left = right + 1;
}
}
return Traverse(queue);
}
private static TreeNode? Traverse(Queue<int?> queue)
{
if (!queue.TryDequeue(out var num) || num == null)
{
return null;
}
return new TreeNode(num)
{
Left = Traverse(queue),
Right = Traverse(queue),
};
}
}