Advertisement
Guest User

talya2

a guest
Jul 25th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace BTreeSerializationLib
  7. {
  8. public class TreeNode
  9. {
  10. public TreeNode() { }
  11. public TreeNode(string value) { Value = value; }
  12. public TreeNode(string value, TreeNode left, TreeNode right) : this(value) { Left = left; Right = right; }
  13.  
  14. public string Value { get; set; }
  15. public TreeNode Left { get; set; }
  16. public TreeNode Right { get; set; }
  17.  
  18. public String serialize()
  19. {
  20. StringBuilder str = new StringBuilder();
  21. serialize(str, this, new HashSet<TreeNode>());
  22. return str.ToString();
  23. }
  24.  
  25. private void serialize(StringBuilder str, TreeNode node, HashSet<TreeNode> nodes)
  26. {
  27. if(node == null)
  28. {
  29. str.Append("null;");
  30. return;
  31. }
  32. if(nodes.Contains(node))
  33. throw new BTreeSerializationException();
  34.  
  35. nodes.Add(node);
  36.  
  37. str.Append(node.Value).Append(";");
  38. serialize(str, node.Left, nodes);
  39. serialize(str, node.Right, nodes);
  40. }
  41.  
  42. public static TreeNode deSerialize(string serialized)
  43. {
  44. if (string.IsNullOrEmpty(serialized) || !serialized.EndsWith(";"))
  45. throw new BTreeSerializationException();
  46.  
  47. string[] vals = serialized.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
  48.  
  49. Queue<string> q = new Queue<string>(vals);
  50. TreeNode node = deSerialize(q);
  51.  
  52. if(q.Count() > 0)
  53. throw new BTreeSerializationException();
  54.  
  55. return node;
  56. }
  57.  
  58. private static TreeNode deSerialize(Queue<string> vals)
  59. {
  60. if (vals.Count == 0)
  61. throw new BTreeSerializationException();
  62.  
  63. string val = vals.Dequeue();
  64. if (val == "null")
  65. return null;
  66.  
  67. return new TreeNode(val, deSerialize(vals), deSerialize(vals));
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement