일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- t1
- attribute
- 프로그래머스
- iterator
- 컴퓨터의 구조
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- 43. Multiply Strings
- data science
- 315. Count of Smaller Numbers After Self
- 715. Range Module
- kaggle
- Substring with Concatenation of All Words
- Generator
- Decorator
- Regular Expression
- 30. Substring with Concatenation of All Words
- 시바견
- Class
- 운영체제
- LeetCode
- Convert Sorted List to Binary Search Tree
- shiba
- Python Code
- Python
- Protocol
- Python Implementation
- 파이썬
- concurrency
- DWG
Archives
- Today
- Total
Scribbling
[C++] to_string, deque, string split 본문
LeetCode 297. Serialize and Deserialize Binary Tree
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
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 |