Shortest preorder solution


  • 0
    C

    class Codec {
    public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if (root == NULL) return "#";
        return to_string(root->val) + " " + serialize(root->left) + " " + serialize(root->right);
    }
    
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        stringstream ss(data.c_str());
        return deserialize(ss);
    }
    TreeNode* deserialize(stringstream& data) {
        string num;
        data >> num;
        if (num == "#") return NULL;
        else {
            TreeNode* root = new TreeNode(stoi(num));
            root->left = deserialize(data);
            root->right = deserialize(data);
            return root;
        }
    }
    

    };


  • 0
    X

    We can further shorten the string by:

    1. Use empty string to represent NULL.
    2. Use different symbols to start left and right node. For example, "[" for left node, "{" for right node.
      Example:
    Tree:
    {1, {11, NULL, {112, NULL, NULL}}, {12, {121, {1211, NULL, NULL}, NULL}}}
    encoded string:
    1[11{112{12[121[1211
    

Log in to reply
 

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