-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0297-Serialize-and-deserialize-binary-tree.cs
More file actions
85 lines (68 loc) · 2.51 KB
/
0297-Serialize-and-deserialize-binary-tree.cs
File metadata and controls
85 lines (68 loc) · 2.51 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
77
78
79
80
81
82
83
84
85
using Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0297.Serialize_and_deserialize_binary_tree
{
public class _0297_Serialize_and_deserialize_binary_tree
{
public class Codec
{
// Encodes a tree to a single string.
public string serialize(TreeNode root)
{
if (root == null) return string.Empty;
List<string> list = new List<string>();
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0)
{
TreeNode curr = queue.Dequeue();
list.Add(curr == null ? "" : curr.val.ToString());
if (curr != null)
{
queue.Enqueue(curr.left);
queue.Enqueue(curr.right);
}
}
return string.Join(',', list.ToArray());
}
// Decodes your encoded data to tree.
public TreeNode deserialize(string data)
{
if (data == null || data.Length == 0) return null;
string[] arr = data.Split(',');
TreeNode root = new TreeNode(int.Parse(arr[0]));
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int i = 1;
while (i < arr.Length)
{
TreeNode node = queue.Dequeue();
if (node != null)
{
TreeNode leftNode;
TreeNode rightNode;
// current
if (arr[i] == String.Empty)
leftNode = null;
else
leftNode = new TreeNode(int.Parse(arr[i]));
// next
if (arr[i + 1] == String.Empty)
rightNode = null;
else
rightNode = new TreeNode(int.Parse(arr[i + 1]));
// point to node
node.left = leftNode;
node.right = rightNode;
queue.Enqueue(node.left);
queue.Enqueue(node.right);
i += 2;
}
}
return root;
}
}
}
}