leetcode297

时间:2024-01-19 19:48:02
 public class Codec
{
// Encodes a tree to a single string.
public string serialize(TreeNode root)
{
if (root == null)
return ""; Queue<TreeNode> queue = new Queue<TreeNode>();
StringBuilder result = new StringBuilder(); queue.Enqueue(root);
while (true)
{
if (queue.Count() == )
break; int nodesAtLevel = queue.Count();
StringBuilder list = new StringBuilder();
for (int i = ; i < nodesAtLevel; i++)
{
var node = queue.Dequeue();
if (node != null)
{
list.Append(node.val.ToString() + ",");
if (node.left != null)
queue.Enqueue(node.left);
else
queue.Enqueue(null); if (node.right != null)
queue.Enqueue(node.right);
else
queue.Enqueue(null);
}
else
{
list.Append("null" + ",");
} }
result.Append(list.ToString());
}
result.Remove(result.Length - , );
return result.ToString();
} // Decodes your encoded data to tree.
public TreeNode deserialize(string data)
{
if (data.Length == )
return null;
Queue<TreeNode> queue = new Queue<TreeNode>();
var tlist = data.Split(',');
var count = tlist.Length; foreach (var l in tlist)
{
if (l != "null")
{
var t = new TreeNode(int.Parse(l));
queue.Enqueue(t);
}
else
{
queue.Enqueue(null);
}
}
var root = queue.Dequeue();
var list = new List<TreeNode>();
list.Add(root);
while (queue.Any())
{
var temp = new List<TreeNode>();
for (int i = ; i < list.Count; i++)
{
var p = list[i];
var left = queue.Dequeue();
if (left != null)
{
p.left = left;
}
var right = queue.Dequeue();
if (right != null)
{
p.right = right;
}
if (p.left != null)
{
temp.Add(p.left);
}
if (p.right != null)
{
temp.Add(p.right);
}
}
list = temp;
}
return root;
}
}

相关文章