1 public class Codec 2 { 3 // Encodes a tree to a single string. 4 public string serialize(TreeNode root) 5 { 6 if (root == null) 7 return ""; 8 9 Queue<TreeNode> queue = new Queue<TreeNode>(); 10 StringBuilder result = new StringBuilder(); 11 12 queue.Enqueue(root); 13 while (true) 14 { 15 if (queue.Count() == 0) 16 break; 17 18 int nodesAtLevel = queue.Count(); 19 StringBuilder list = new StringBuilder(); 20 for (int i = 0; i < nodesAtLevel; i++) 21 { 22 var node = queue.Dequeue(); 23 if (node != null) 24 { 25 list.Append(node.val.ToString() + ","); 26 if (node.left != null) 27 queue.Enqueue(node.left); 28 else 29 queue.Enqueue(null); 30 31 if (node.right != null) 32 queue.Enqueue(node.right); 33 else 34 queue.Enqueue(null); 35 } 36 else 37 { 38 list.Append("null" + ","); 39 } 40 41 } 42 result.Append(list.ToString()); 43 } 44 result.Remove(result.Length - 1, 1); 45 return result.ToString(); 46 } 47 48 // Decodes your encoded data to tree. 49 public TreeNode deserialize(string data) 50 { 51 if (data.Length == 0) 52 return null; 53 Queue<TreeNode> queue = new Queue<TreeNode>(); 54 var tlist = data.Split(','); 55 var count = tlist.Length; 56 57 foreach (var l in tlist) 58 { 59 if (l != "null") 60 { 61 var t = new TreeNode(int.Parse(l)); 62 queue.Enqueue(t); 63 } 64 else 65 { 66 queue.Enqueue(null); 67 } 68 } 69 var root = queue.Dequeue(); 70 var list = new List<TreeNode>(); 71 list.Add(root); 72 while (queue.Any()) 73 { 74 var temp = new List<TreeNode>(); 75 for (int i = 0; i < list.Count; i++) 76 { 77 var p = list[i]; 78 var left = queue.Dequeue(); 79 if (left != null) 80 { 81 p.left = left; 82 } 83 var right = queue.Dequeue(); 84 if (right != null) 85 { 86 p.right = right; 87 } 88 if (p.left != null) 89 { 90 temp.Add(p.left); 91 } 92 if (p.right != null) 93 { 94 temp.Add(p.right); 95 } 96 } 97 list = temp; 98 } 99 return root; 100 } 101 }