Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace BTreeSerializationLib
- {
- public class TreeNode
- {
- public TreeNode() { }
- public TreeNode(string value) { Value = value; }
- public TreeNode(string value, TreeNode left, TreeNode right) : this(value) { Left = left; Right = right; }
- public string Value { get; set; }
- public TreeNode Left { get; set; }
- public TreeNode Right { get; set; }
- public String serialize()
- {
- StringBuilder str = new StringBuilder();
- serialize(str, this, new HashSet<TreeNode>());
- return str.ToString();
- }
- private void serialize(StringBuilder str, TreeNode node, HashSet<TreeNode> nodes)
- {
- if(node == null)
- {
- str.Append("null;");
- return;
- }
- if(nodes.Contains(node))
- throw new BTreeSerializationException();
- nodes.Add(node);
- str.Append(node.Value).Append(";");
- serialize(str, node.Left, nodes);
- serialize(str, node.Right, nodes);
- }
- public static TreeNode deSerialize(string serialized)
- {
- if (string.IsNullOrEmpty(serialized) || !serialized.EndsWith(";"))
- throw new BTreeSerializationException();
- string[] vals = serialized.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
- Queue<string> q = new Queue<string>(vals);
- TreeNode node = deSerialize(q);
- if(q.Count() > 0)
- throw new BTreeSerializationException();
- return node;
- }
- private static TreeNode deSerialize(Queue<string> vals)
- {
- if (vals.Count == 0)
- throw new BTreeSerializationException();
- string val = vals.Dequeue();
- if (val == "null")
- return null;
- return new TreeNode(val, deSerialize(vals), deSerialize(vals));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement