在C#中,可以使用以下代碼來反序列化一個二叉樹:
using System;
using System.Collections.Generic;
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
}
}
public class BinaryTreeSerializer
{
public string Serialize(TreeNode root)
{
if (root == null)
{
return "null";
}
return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);
}
public TreeNode Deserialize(string data)
{
Queue<string> nodes = new Queue<string>(data.Split(','));
return DeserializeHelper(nodes);
}
private TreeNode DeserializeHelper(Queue<string> nodes)
{
string val = nodes.Dequeue();
if (val == "null")
{
return null;
}
TreeNode node = new TreeNode(int.Parse(val));
node.left = DeserializeHelper(nodes);
node.right = DeserializeHelper(nodes);
return node;
}
}
public class Program
{
public static void Main()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
BinaryTreeSerializer serializer = new BinaryTreeSerializer();
string serializedData = serializer.Serialize(root);
Console.WriteLine(serializedData);
TreeNode deserializedRoot = serializer.Deserialize(serializedData);
Console.WriteLine(deserializedRoot.val); // Output: 1
}
}
在上面的代碼中,我們定義了一個TreeNode
類來表示二叉樹的節點,然后定義了一個BinaryTreeSerializer
類來實現二叉樹的序列化和反序列化功能。Serialize
方法用于將二叉樹序列化為字符串,Deserialize
方法用于將字符串反序列化為二叉樹。最后,在Main
方法中我們演示了如何使用這兩個方法來序列化和反序列化一個二叉樹。