LeetCode 428. Serialize and Deserialize N-ary Tree
原题链接
困难
作者:
JasonSun
,
2020-02-13 06:26:34
,
所有人可见
,
阅读 780
Algorithm (Depth First Search)
- We traverse the whole tree in preorder, and at each node we accumulate its value and children size to a string (note that the two numebrs should be delimited by a whitespace), which we denote
acc
. When we finish traversing, we return acc
. If one of the node is a null pointer, we write #
.
- To reconstruct the tree, we essentially do the same preorder traversal we did before but this time with a tokenizer to read the input string. At each step fo the traversal,
- If we encounter
#
, we construct and return a null pointer.
- Otherwise, we build a node with next interger noken and recurse down (child information will be read using the tokenizer as well).
Code (Cpp17)
class tokenizer {
private:
string data_;
int cursor_;
public:
tokenizer(const string& str) : data_(str), cursor_(0){};
private:
void ready() {
if (data_[cursor_] == ' ' and cursor_ + 1 < size(data_)) {
cursor_++;
ready();
}
}
char read() { return data_[cursor_++]; };
public:
bool has_next() { return cursor_ < size(data_); }
char peek() { return cursor_ < size(data_) ? data_[cursor_] : '\n'; };
void consume() { read(); };
template <typename T, typename std::enable_if_t<std::is_same_v<string, T>>* = nullptr>
T next() {
ready();
string result{};
while (has_next() and isalpha(peek()))
result.push_back(read());
return result;
}
template <typename T, typename std::enable_if_t<std::is_same_v<int, T>>* = nullptr>
T next() {
ready();
int acc = 0;
while (has_next() and isdigit(peek()))
acc = (acc * 10) + read() - '0';
return acc;
}
};
class Codec {
public:
// Encodes a tree to a single string.
string serialize(Node* root) {
auto acc = std::string{};
std::function<void(Node*)> go = [&](Node * node) {
if (node == nullptr)
acc += std::string{'#'};
else {
acc += std::to_string(node->val) + " " + std::to_string(std::size(node->children)) + " ";
for (const auto ch : node->children)
go(ch);
}
};
return go(root), acc;
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
auto token = tokenizer(data);
std::function<Node*(void)> go = [&]() -> Node* {
if (token.peek() == '#')
return (token.consume(), nullptr);
else {
const auto val = token.next<int>();
const auto children_size = token.next<int>();
Node* node = new Node(val, {});
for (int i = 0; i < children_size; ++i)
node->children.push_back(go());
return node;
}
};
return go();
}
};
神,请收下我的膝盖。
😂 😂 😂
不敢不敢 互相学习
只写hard的大佬