re: Daily Coding Problem #3 VIEW POST

FULL DISCUSSION
 

Here's my C# solution

using System;

namespace DailyCodingProblem3
{
    class Node
    {
        public string Val { get; set; }
        public Node Left { get; set; }
        public Node Right { get; set; }

        public Node(string val, Node left = null, Node right = null)
        {
            Val = val;
            Left = left;
            Right = right;
        }
    }

    class Program
    {
        public static string Serialize(Node node)
        {
            if (node == null)
            {
                return "-";
            }

            string ret = $"{node.Val}-";
            ret += Serialize(node.Left);
            ret += Serialize(node.Right);

            return ret;
        }

        public static Node Deserialize(ref string str)
        {
            if (str.Length == 0 || str.StartsWith("-"))
            {
                return null;
            }

            var val = str.Split('-')[0];

            str = str.Substring(str.IndexOf('-') + 1);
            var left = Deserialize(ref str);

            str = str.Substring(str.IndexOf('-') + 1);
            var right = Deserialize(ref str);

            return new Node(val, left, right);
        }

        static void Main()
        {
            var node = new Node("root", new Node("left", null, new Node("left.right", new Node("left.right.left"))), new Node("right"));
            var ret = Serialize(node);

            Console.WriteLine(ret);
            Console.WriteLine(Serialize(Deserialize(ref ret)));
        }
    }
}
code of conduct - report abuse