Scribbling

[C++] to_string, deque, string split 본문

Computer Science/C++

[C++] to_string, deque, string split

focalpoint 2023. 8. 24. 06:59

 

LeetCode 297. Serialize and Deserialize Binary Tree

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

 

Serialize and Deserialize Binary Tree - LeetCode

Can you solve this real interview question? Serialize and Deserialize Binary Tree - Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a n

leetcode.com

class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if (root == NULL) {
            return "N";
        }
        string left = serialize(root->left);
        string right = serialize(root->right);
        return to_string(root->val) + "."  + left + "." + right;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        deque<string> q = split(data, ".");
        return helper(q);
    }

    TreeNode* helper(deque<string>& q) {
        string value = q.front();
        q.pop_front();
        if (value == "N") {
            return NULL;
        }
        TreeNode* ret = new TreeNode(stoi(value));
        ret->left = helper(q);
        ret->right = helper(q);
        return ret;
    }

    deque<string> split(string s, string delimiter) {
        deque<string> ret;
        size_t pos_start = 0, pos_end, delim_len = delimiter.length();
        string token;
        while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
            token = s.substr(pos_start, pos_end - pos_start);
            pos_start = pos_end + delim_len;
            ret.push_back(token);
        }
        ret.push_back(s.substr(pos_start));
        return ret;
    }
};

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

'Computer Science > C++' 카테고리의 다른 글

[C++] vector sum, vector max  (0) 2023.08.31
[C++] ostringstream, isdigit  (0) 2023.08.29
[C++] istringstream  (0) 2023.08.22
[C++] Chapter 2: Types  (0) 2023.08.21
[C++] Load Balancing  (0) 2023.08.19