Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Program p = new Program();

            TreeNode node = new TreeNode(-1) { left = new TreeNode(-2), right = new TreeNode(-3) };
            Console.WriteLine(p.serialize(node));
            node = p.deserialize(p.serialize(node));
        }
Exemplo n.º 2
0
 private TreeNode deserializeInternal(string data, int start, out int i)
 {
     TreeNode node = null;
     int count = 0;
     bool rightFlag = false;
     bool neg = false;
     i = start;
     while (++i < data.Length)
     {
         if (data[i] == ')')
         {
             break;
         }
         else if (data[i] == ',')
         {
             if (node == null)
                 node = new TreeNode(neg ? -count : count);
             else
                 rightFlag = true;
         }
         else if (data[i] == '(')
         {
             if (rightFlag)
                 node.right = deserializeInternal(data, i, out i);
             else
                 node.left = deserializeInternal(data, i, out i);
         }
         else if (data[i] == '-')
         {
             neg = true;
         }
         else
         {
             int n = data[i] - '0';
             count = 10 * count + n;
         }
     }
     return node;
 }
Exemplo n.º 3
0
 private void serializeInternal(StringBuilder sb, TreeNode root)
 {
     if (root == null)
         return;
     sb.Append('(');
     sb.Append(root.val);
     sb.Append(',');
     serializeInternal(sb, root.left);
     sb.Append(',');
     serializeInternal(sb, root.right);
     sb.Append(')');
 }
Exemplo n.º 4
0
 // Encodes a tree to a single string.
 public string serialize(TreeNode root)
 {
     StringBuilder sb = new StringBuilder();
     serializeInternal(sb, root);
     return sb.ToString();
 }