阅读量:0
在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
方法中我们演示了如何使用这两个方法来序列化和反序列化一个二叉树。