My C# Solution using Preorder DFS


  • 0

    public class Codec
    {

    void preorderSerialize(TreeNode node, StringBuilder sb)
    {
        if (node == null)
        {
            sb.Append("#,");
            return;
        }
    
        sb.Append(node.val); sb.Append(",");
    
        preorderSerialize(node.left, sb);
        preorderSerialize(node.right, sb);
    }
    
    TreeNode preorderDeserialize(string[] nodes, ref int pos)
    {
        if (nodes[pos] == "#")
        {
            pos++;
            return null;
        }
        var node = new TreeNode(int.Parse(nodes[pos++]));
        node.left = preorderDeserialize(nodes, ref pos);
        node.right = preorderDeserialize(nodes, ref pos);
        return node;
    }
    
    // Encodes a tree to a single string.
    public string serialize(TreeNode root)
    {
        var sb = new StringBuilder();
        preorderSerialize(root, sb);
        return sb.ToString().Trim(','); //remove trailing comma
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(string data)
    {
        int pos = 0;
        var tokens = data.Split(',');
        return preorderDeserialize(tokens, ref pos);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.