Concise C++ preorder with pointer type cast 26ms 93.07%


  • 0
    L
    
    class Codec {
    public:
        int i; int n;
        string serialize(TreeNode* root) {
            if (!root) return "";
            return string(reinterpret_cast<char*>(&(root->val)), 4) + serialize(root->left) + serialize(root->right);
        }
        TreeNode* deserialize(string data) {
            i = 0, n = data.length() / 4;
            return _deserialize(reinterpret_cast<const int*>(data.c_str()), INT_MIN, INT_MAX);
        }  
        TreeNode* _deserialize(const int* data, int lower, int upper)
        {
            if (i == n || data[i] < lower || data[i] > upper) return NULL;
            int val = data[i++];
            TreeNode* root = new TreeNode(val);
            root->left = _deserialize(data, lower, val);
            root->right = _deserialize(data, val, upper);
            return root;
        }
    };
    
    

Log in to reply
 

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